Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect $GOHOSTOS and $GOHOSTARCH at runtime?

Tags:

go

How do I detect the value of $GOHOSTOS and $GOHOSTARCH at runtime on any system a go binary is running? Please note that I want to detect these values even if there is no go compiler installation on a host.

like image 903
codefx Avatar asked Sep 05 '25 19:09

codefx


2 Answers

$GOHOSTOS and $GOHOSTARCH ( serve default values for GOOS and GOARCH respectively) are used while building of go programs and do not influence the execution of the run-time system.

GOOS and GOARCH are recorded at compile time and made available by constants runtime.GOOS and runtime.GOARCH. You may want to check these constants.

like image 58
ppp Avatar answered Sep 08 '25 11:09

ppp


Short version, you can't.

Long version, you can create a build script that embeds the info in your code, for example:

- main.go:

package main

import (
    "fmt"
    "runtime"
)

var (
    hostOS   string
    hostArch string
)

func main() {
    fmt.Println("runtime values:", runtime.GOOS, runtime.GOARCH)
    fmt.Println("build time values:", hostOS, hostArch)
}

- build.sh

#!/bin/sh
# replace main. with whatever package you're using
go build -ldflags "-X main.hostOS=$(go env GOHOSTOS) -X main.hostArch=$(go env GOHOSTARCH)" $*

- output:

$ env GOARCH=386 ./build.sh
$ ./tmp
runtime values: linux 386
build time values: linux amd64
like image 25
OneOfOne Avatar answered Sep 08 '25 10:09

OneOfOne