DEV Community

natamacm
natamacm

Posted on

Detect operating system in Go

#go

When you code in Go, it runs on an operating system. From within a Go program, you can fetch the operating system.

If golang is not installed you should install Go with your package manager, something like:

sudo dnf install go    
sudo apt-get install go

depending on your operating system. If go is already installed you can use the code below.

We load the module runtime, which can fetch the current operating system.

package main

import (
        "log"
        "runtime"
)

// Reference: http://stackoverflow.com/questions/19847594/how-to-reliably-detect-os-platform-in-go
func main() {
        log.Printf("%v\n", runtime.GOOS) // output windows or linux
}

You can run your program with the command:

go run example.go

In my case the program outputs:

2020/05/09 20:06:46 linux

Program exited.

Simple, but neat.

Related links:

Top comments (0)