Detect if Code is Running On Windows (at Runtime)

· 136 words · 1 minute read

On of the advantages of using Go is it’s cross-platform support, the ability to write the code once and have it work across many operating systems. However, there are times when you’ll need to change the route through your code based which OS is running it. If you’re needing to do this on a large scale there are better, more manageable ways, but for tiny changes this works fine.

This snippet uses the GOOS flag within the runtime package, which is also used at compile time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
    "fmt"
    "runtime"
)

func main() {

    if runtime.GOOS == "windows" {
        fmt.Println("You are running on Windows")
    } else {
        fmt.Println("You are running on an OS other than Windows")
    }

}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!