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)

Make Your Github Profile Stand Out

Github is great, but have you considered how to make yours more attractive for potential employers or other visitors? Even non-tech ones like recruiters!

Take a couple of hours and show your best side as a person - and a programmer.