Standard library / go/build
go/build.Context
Models a target build environment, including OS, architecture, tags and filesystem hooks. Expected stdout: 'linux amd64 false\n'.
Formal Syntax & Structure
go syntaxgo
type Context struct { GOARCH string GOOS string GOROOT string GOPATH string
Dir string
CgoEnabled bool UseAllFiles bool Compiler string
BuildTags []string ToolTags []string ReleaseTags []string
InstallSuffix string
JoinPath func(elem ...string) string
SplitPathList func(list string) []string
IsAbsPath func(path string) bool
IsDir func(path string) bool
HasSubdir func(root, dir string) (rel string, ok bool)
ReadDir func(dir string) ([]fs.FileInfo, error)
OpenFile func(path string) (io.ReadCloser, error)}Working Example
Example Snippetgo
package main
import ( "fmt" "go/build" "os" "path/filepath")
func check(e error) { if e != nil { panic(e) }}func directory() (string, func()) { d, e := os.MkdirTemp("", "build-demo-") check(e) for n, s := range map[string]string{"base.go": "package demo\n", "only_linux.go": "package demo\n", "only_windows.go": "package demo\n", "feature.go": "//go:build feature\n\npackage demo\n"} { check(os.WriteFile(filepath.Join(d, n), []byte(s), 0600)) } return d, func() { check(os.RemoveAll(d)) }}func target() build.Context { c := build.Default c.GOOS = "linux" c.GOARCH = "amd64" c.CgoEnabled = false c.BuildTags = nil return c}
func main() { c := target(); fmt.Println(c.GOOS, c.GOARCH, c.CgoEnabled) }