GOOS=js
- Go course
- Expert
- Lesson 26/34
- 4 min
Learn to compile with GOOS=js GOARCH=wasm.
GOOS and GOARCH
Cross-compiling in Go uses two environment variables; no extra toolchain is needed (with cgo off):
GOOS=linux GOARCH=arm64 go build # Raspberry Pi, AWS Graviton
GOOS=windows GOARCH=amd64 go build # .exe
GOOS=darwin GOARCH=arm64 go build # Apple Silicon
go tool dist list # all targetsFile name suffixes (_windows.go, _wasm.go) and //go:build lines select target-specific code.
Behavior per target
To implement the same API differently per target, two files share one function name:
// depo_js.go
//go:build js
func kaydet(k, v string) { localStorage.Set(k, v) }
// depo_other.go
//go:build !js
func kaydet(k, v string) { os.WriteFile(k, []byte(v), 0o644) }runtime.GOOS can also be used to query the target at run time.
Practice Text per target
Write platform() string: return "tarayıcı" if runtime.GOOS == "js", otherwise "yerel". Print the result.
Starter code
package main
import (
"fmt"
"runtime"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"runtime"
)
func platform() string {
if runtime.GOOS == "js" {
return "tarayıcı"
}
return "yerel"
}
func main() {
fmt.Println(platform())
}Expected output
yerel
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is a file named <code>dosya_js.go</code> compiled?
- Only in tests
- Never
- Only when GOOS=js Correct answer
- Always
Explanation: The _GOOS and _GOARCH suffixes are implicit build constraints; the file joins the build only for a matching target.
2 List the targets
go tool dist ____
go tool dist list
Explanation: go tool dist list prints every supported GOOS/GOARCH pair.
3 Target pair
| Term | Meaning |
|---|---|
linux/arm64 |
Raspberry Pi, Graviton |
windows/amd64 |
.exe file |
js/wasm |
Browser |
darwin/arm64 |
Apple Silicon |