Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

Detect OS in Go (Golang)

Posted on February 23, 2023February 23, 2023 by admin

runtime.GOOS constant can be used to detect the OS at runtime since this constant gets set only at runtime.

runtime.GOARCH can be used to know the architecture target of the running program.

To see all possible combinations of GOOS and GOARCH, run the command

go tool dist list

Below is the code to know the currently running OS:

package main
import (
"fmt"
"runtime"
)
func main() {
os := runtime.GOOS
switch os {
case "windows":
fmt.Println("Windows")
case "darwin":
fmt.Println("MAC operating system")
case "linux":
fmt.Println("Linux")
default:
fmt.Printf("%s.\n", os)
}
}

Output:

Your current operating system

Popular Articles

Golang Comprehensive Tutorial Series

All Design Patterns in Go (Golang)

Slice in golang

Variables in Go (Golang) – Complete Guide

OOP: Inheritance in GOLANG complete guide

Using Context Package in GO (Golang) – Complete Guide

All data types in Golang with examples

Understanding time and date in Go (Golang) – Complete Guide

©2024 Welcome To Golang By Example | Design: Web XP