Day 0: The Training Ground
Goal: Set up the toolchain, editor and linter and build the first tool
hallowith a built-in version · Duration: approx. 60 min · Prerequisite: none
Briefing
- Go is a single toolchain:
go build,go run,go test,go vet,go fmt,go doc– all in thegocommand. - A module (
go.mod) is your project; every tool in this book is its own moduleexample.com/<tool>. - A program is
package mainwithfunc main(). The result is a static binary – no interpreter, no venv. - The build sets the version via
-ldflags "-X main.version=…", not the code. - Quality comes from tools:
gofmt,go vet,golangci-lint.
main.go ──go build──► bin/hallo (one binary, ~2 MB)
▲ │
-ldflags "-X main.version=0.1.0" ./bin/hallo -version ─► hallo 0.1.0
Drill 1: Check the toolchain
go version
go env GOVERSION GOOS GOARCHExpected:
go version go1.26.9 darwin/arm64
go1.26.9
darwin
arm64
Why? GOOS/GOARCH determine what you build
for – you use that on Day 14 for cross-compiles. Your projects live
wherever you like; go env GOPATH (usually
~/go) is now only a cache and the destination for
go install.
Tip: If
go versionshows something older than 1.26:brew upgrade go. If ago.modnames a newer version, Go downloads the matching toolchain itself (GOTOOLCHAIN=auto, the default).
Save your progress? Sign up for free
Drill 2: Editor with gopls
Every serious Go editor talks to gopls, the official language server: autocompletion, go to definition, rename, errors as you type.
go install golang.org/x/tools/[email protected]
gopls versionExpected:
golang.org/x/tools/gopls v0.23.0
In VS Code you install the “Go” extension (from the Go team); it finds gopls on its own. GoLand ships its own engine and does not need gopls.
Tip: If
~/go/binis not in yourPATH, the shell won’t findgopls. The editor will – it asksgo env GOPATH.
Save your progress? Sign up for free
Drill 3: Create a module
mkdir -p ~/go-lab/tag00-hallo && cd ~/go-lab/tag00-hallo
go mod init example.com/hallo
cat go.modExpected:
go: creating new go.mod: module example.com/hallo
module example.com/hallo
go 1.26.9
Why? The module path is the import prefix for all packages in the
project. example.com/… is reserved and never collides with
real repos; for real projects you use the repo path,
e.g. github.com/<user>/hallo.
Save your progress? Sign up for free
Drill 4: The first program
mkdir -p cmd/hallo
cat > cmd/hallo/main.go <<'EOF'
// hallo greets you and tells you its version.
// Day 0 from "Go hands-on".
package main
import (
"flag"
"fmt"
"os"
"runtime"
)
// version is set by the build via -ldflags "-X main.version=...".
var version = "dev"
func main() {
name := flag.String("name", "Welt", "wen hallo begrüßt")
showVersion := flag.Bool("version", false, "Version ausgeben und beenden")
flag.Parse()
if *showVersion {
fmt.Printf("hallo %s (%s %s/%s)\n",
version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
return
}
if *name == "" {
fmt.Fprintln(os.Stderr, "hallo: -name darf nicht leer sein")
os.Exit(2)
}
fmt.Printf("Hallo, %s!\n", *name)
}
EOF
go run ./cmd/hallo
go run ./cmd/hallo -name ThomasExpected:
Hallo, Welt!
Hallo, Thomas!
Why? flag.String returns a pointer
(*string); only flag.Parse() fills it, and
*name reads the value. Capitalized names like
fmt.Printf are exported; lowercase ones like
version are visible only within their own package.
Save your progress? Sign up for free
Drill 5: Flags, help and exit codes
Built binaries behave like any Unix tool. Build one and check the exit codes:
go build -o bin/hallo ./cmd/hallo
./bin/hallo -h; echo "exit=$?"
./bin/hallo -name ""; echo "exit=$?"
go run ./cmd/hallo -name ""; echo "exit=$?"Expected:
Usage of ./bin/hallo:
-name string
wen hallo begrüßt (default "Welt")
-version
Version ausgeben und beenden
exit=0
hallo: -name darf nicht leer sein
exit=2
hallo: -name darf nicht leer sein
exit status 2
exit=1
Why? The flag package generates the help from your
definitions (“wen hallo begrüßt” means “whom hallo greets”, “Version
ausgeben und beenden” means “print version and exit”).
go run reports the exit code only as text and itself exits
with 1 – for scripts and CI, always check the built binary. Convention
in this book: 0 = ok, 1 = error while working, 2 = wrong invocation.
Save your progress? Sign up for free
Drill 6: Version via -ldflags
./bin/hallo -version
go build -ldflags "-X main.version=0.1.0" -o bin/hallo ./cmd/hallo
./bin/hallo -version
ls -lh bin/hallo | awk '{print $5}'
go build -ldflags "-s -w -X main.version=0.1.0" -o bin/hallo ./cmd/hallo
ls -lh bin/hallo | awk '{print $5}'
go version -m bin/hallo | head -6Expected:
hallo dev (go1.26.9 darwin/arm64)
hallo 0.1.0 (go1.26.9 darwin/arm64)
2,5M
1,7M
bin/hallo: go1.26.9
path example.com/hallo/cmd/hallo
mod example.com/hallo (devel)
build -buildmode=exe
build -compiler=gc
build -ldflags="-s -w -X main.version=0.1.0"
Why? -X paket.variable=wert overwrites a string
variable at link time – the code stays unchanged.
-s -w strips the symbol and debug tables (smaller, but
harder to debug). go version -m reads the embedded build
info from any Go binary – handy when a customer asks “what was this
built with?”.
Save your progress? Sign up for free
Drill 7: Quality control
First the built-in tools, then the linter. Plant a bug that the compiler does not find:
perl -pi -e 's/"Hallo, %s!\\n"/"Hallo, %d!\\n"/' cmd/hallo/main.go
go build ./... && echo "kompiliert trotzdem"
go vet ./...
perl -pi -e 's/"Hallo, %d!\\n"/"Hallo, %s!\\n"/' cmd/hallo/main.go
go vet ./... && gofmt -l . && echo "sauber"Expected:
kompiliert trotzdem
cmd/hallo/main.go:29:21: fmt.Printf format %d has arg *name of wrong type string
sauber
For golangci-lint you create a small wrapper script.
go run …@version builds the linter at a pinned version into
the Go cache – no global installation, and every day uses the same
version:
mkdir -p ~/go-lab/bin
cat > ~/go-lab/bin/lint <<'EOF'
#!/usr/bin/env bash
# golangci-lint at a pinned version – without a global installation
exec go run github.com/golangci/golangci-lint/v2/cmd/[email protected] "$@"
EOF
chmod +x ~/go-lab/bin/lint
~/go-lab/bin/lint version
~/go-lab/bin/lint run ./...
go fix -diff ./... && echo "nichts zu modernisieren"Expected (the first run builds for about 1–2 minutes, shortened):
golangci-lint has version 2.14.0 built with go1.26.9 from (unknown, ...)
0 issues.
nichts zu modernisieren
Why? gofmt -l lists unformatted files – empty means
good; your editor formats on save. golangci-lint bundles
govet, errcheck, staticcheck,
unused and ineffassign (standard set). Since
Go 1.26, go fix comes with “modernizers” that lift old code
to current language features.
Save your progress? Sign up for free
Drill 8: Docs without a browser
The standard library is large and well documented – right in the terminal:
go doc flag.String
go doc -short os | grep -E 'func (Exit|Getenv)\('
go list -f '{{.ImportPath}} {{.Imports}}' ./cmd/hallo
go list std | wc -lExpected:
package flag // import "flag"
func String(name string, value string, usage string) *string
String defines a string flag with specified name, default value, and usage
string. The return value is the address of a string variable that stores the
value of the flag.
func Exit(code int)
func Getenv(key string) string
example.com/hallo/cmd/hallo [flag fmt os runtime]
360
Why? Around 360 standard library packages cover HTTP, JSON, crypto,
tests and logging – which is why the tools in this book get by with few
dependencies. go doc works the same way for your own
packages (Day 2).
To put it in context with what you know from Bash and Python:
| Task | Bash | Python | Go |
|---|---|---|---|
| Arguments | getopts |
argparse |
flag (Day 5: cobra) |
| Exit code | exit 2 |
sys.exit(2) |
os.Exit(2) |
| Environment | $HOME |
os.environ |
os.Getenv("HOME") |
| Shipping | script + tools | venv/pipx | one binary |
Save your progress? Sign up for free
Drill 9: The tool is done
cd ~/go-lab/tag00-hallo
go build -ldflags "-s -w -X main.version=0.1.0" -o bin/hallo ./cmd/hallo
./bin/hallo -name "Platform-Team"
./bin/hallo -versionExpected:
Hallo, Platform-Team!
hallo 0.1.0 (go1.26.9 darwin/arm64)
Your module now looks like this:
tag00-hallo/
├── bin/hallo
├── cmd/hallo/main.go
└── go.mod
The finished code of every day is available for comparison in the companion code on GitHub. Get it now; first you type it yourself, then you look:
git clone https://github.com/thomaszachmann/go-zum-anfassen.git ~/go-zum-anfassen
ls -1 ~/go-zum-anfassen/tag00-halloExpected:
Cloning into '…/go-zum-anfassen'...
cmd
go.mod
The folders are named like yours in ~/go-lab. After Day
1, for example,
diff -r ~/go-lab/tag01-wc ~/go-zum-anfassen/tag01-wc shows
where you differ.
Save your progress? Sign up for free
Checkpoint
#!/usr/bin/env bash
check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
cd ~/go-lab/tag00-hallo
check "Go 1.26 aktiv" "go version | grep -q 'go1\.26'"
check "gofmt sauber" "test -z \"\$(gofmt -l .)\""
check "go vet" "go vet ./..."
check "golangci-lint" "~/go-lab/bin/lint run ./..."
check "Version per ldflags" "./bin/hallo -version | grep -q '^hallo 0.1.0'"
check "Exit-Code 2 bei leerem Namen" "./bin/hallo -name ''; test \$? -eq 2"Expected:
✔ Go 1.26 aktiv
✔ gofmt sauber
✔ go vet
✔ golangci-lint
✔ Version per ldflags
✔ Exit-Code 2 bei leerem Namen
Challenge
Without -ldflags, hallo -version should not
show “dev” but the version from Git: the tag if there is one, otherwise
a pseudo-version with the commit. main.go stays
unchanged.
Hint: Since Go 1.18, Go embeds VCS info into the
binary, and since Go 1.24
debug.ReadBuildInfo().Main.Version holds a version from
Git; an init() function runs before main.
Solution
cat > cmd/hallo/buildinfo.go <<'EOF'
package main
import "runtime/debug"
// init runs before main: without -ldflags we take the version from Git.
func init() {
if version != "dev" {
return
}
if bi, ok := debug.ReadBuildInfo(); ok && bi.Main.Version != "(devel)" {
version = bi.Main.Version
}
}
EOF
git init -q && printf 'bin/\n' > .gitignore
git add . && git commit -qm "hallo"
go build -o bin/hallo ./cmd/hallo && ./bin/hallo -version
git tag v0.2.0
go build -o bin/hallo ./cmd/hallo && ./bin/hallo -version
echo "// geändert" >> cmd/hallo/main.go
go build -o bin/hallo ./cmd/hallo && ./bin/hallo -version
git checkout -q cmd/hallo/main.goExpected (timestamp and hash will differ):
hallo v0.0.0-20261010064452-1ace3d653a29 (go1.26.9 darwin/arm64)
hallo v0.2.0 (go1.26.9 darwin/arm64)
hallo v0.2.0+dirty (go1.26.9 darwin/arm64)
An uncommitted state gets +dirty – exactly what you
never want to see in production. -ldflags still takes
precedence, because init then returns early. With
go run there is no VCS info, so it stays “dev”.
Save your progress? Sign up for free
Enterprise Note
- Pin the Go version in the team: the
goandtoolchainlines ingo.mod, the same version in CI (Day 14) – otherwise everyone builds with something different. - Proxy and checksums: companies often set
GOPROXYto an internal proxy (Artifactory, Athens) andGOPRIVATEfor internal repos;GOSUMDBstays on for public modules. - The linter version and
.golangci.ymlbelong in the repo; CI fails on findings, and the same invocation runs locally. - Always take the version from the build (Git tag →
-ldflagsor build info), never maintain it by hand in the code. - No
go install …@lateston build servers: pin versions so builds stay reproducible.