Go for Infrastructure Engineers›Part 1 · Cheat sheet & self-check

Part 1 — The language · wrap-up

Cheat sheet & self-check

Every command from this section on one page.

01 · Why Go for platform work: toolchain, modules and layout

Every day

go mod init github.com/me/kauditStart a module (the import path of your project)
go run .Compile and run the package in this folder
go build -o bin/kaudit .Build a binary
go test ./...Run all tests in the module
go vet ./... && gofmt -l .Static checks and unformatted files
go get k8s.io/client-go@v0.34.0Add or change a dependency version
go mod tidyAdd missing and remove unused dependencies

Build for elsewhere

CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o kaudit-arm64 .Static Linux binary for ARM64, from any machine
go build -ldflags='-s -w -X main.version=1.2.0' .Smaller binary, version stamped at build time
go env GOPATH GOCACHEWhere modules and build cache live

02 · Go through Bash and Python eyes

Syntax at a glance

x := 3Declare and assign (type inferred) inside functions
var nodes []stringDeclare with the zero value (nil slice, ready to append)
nodes = append(nodes, "n1")Add to a slice
counts := map[string]int{}Empty map ready to use
for i, n := range nodes { }Loop over a slice with index and value
if v, ok := counts["n1"]; ok { }Read a map key and check it exists
type Node struct { Name string; Ready bool }Define a struct
func (n Node) String() string { }A method on a type

03 · Errors done right

Patterns

if err != nil { return fmt.Errorf("read %s: %w", path, err) }Add context and keep the original error
if errors.Is(err, os.ErrNotExist) { }Is it (or does it wrap) this specific error?
var nf *NotFoundError; if errors.As(err, &nf) { }Is it (or does it wrap) this error type? Get it
defer f.Close()Run clean-up when the function returns, whatever path it takes
var ErrNoNodes = errors.New("no nodes")A sentinel error callers can test for