如何在运行时检测$ GOHOSTOS和$ GOHOSTARCH?

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.

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

$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.