Get started
Cheatsheet

Go

Go for command-line tools and small services: modules, running and building, types, errors, flags, tests and a standard-library HTTP server.

Practice this path

Modules and the go command

  • go mod init example.com/hello

    Start a module (creates go.mod)

  • go run .

    Compile and run the package in this folder

  • go run . Ada Grace

    Run it with arguments

  • go build -o hello .

    Build an executable called hello

  • go fmt ./...

    Format every file the standard way

  • go vet ./...

    Report suspicious code the compiler accepts

  • go doc strings.Fields

    Read the documentation of a function

  • go version  |  go env GOROOT

    Which Go this is, and where it lives

Types and functions

  • name := "Ada"; var total int = 3

    Declare a variable (short form inside functions)

  • func Add(a, b int) int { return a + b }

    A function with typed parameters and a result

  • func DivMod(a, b int) (int, int) { return a / b, a % b }

    Return several values

  • type Rect struct { W, H float64 }

    A struct type

  • func (r Rect) Area() float64 { return r.W * r.H }

    A method on a type

  • nums := []int{3, 1, 2}; nums = append(nums, 4)

    A slice, and growing it

  • ages := map[string]int{"Ada": 36}; v, ok := ages["Bob"]

    A map, and the comma-ok lookup

  • for i, n := range nums { fmt.Println(i, n) }

    Loop over a slice with index and value

  • strings.Fields(s)  strings.ToLower(s)  strings.Join(parts, "-")

    Common string helpers

Errors

  • n, err := strconv.Atoi(s); if err != nil { return 0, err }

    Check an error right where it happens

  • errors.New("empty input")

    Make a plain error value

  • fmt.Errorf("parse %q: %w", s, err)

    Wrap an error and keep the original

  • var ErrEmpty = errors.New("empty")

    A sentinel error other code can compare with

  • errors.Is(err, ErrEmpty)

    Is this error, or one it wraps, that value?

  • var re *RangeError; errors.As(err, &re)

    Is it, or does it wrap, an error of this type?

  • fmt.Fprintln(os.Stderr, "error:", err); os.Exit(1)

    Report to the error stream and stop with a failure status

Command-line flags

  • name := flag.String("name", "World", "who to greet")

    A string flag with a default and a help text

  • times := flag.Int("times", 1, "how many times")

    An integer flag

  • shout := flag.Bool("shout", false, "upper-case it")

    A boolean flag

  • flag.Parse()

    Read the flags (call it once, before using them)

  • flag.Args()  flag.NArg()

    The words left after the flags

  • os.Args[1:]

    The raw arguments, without the program name

  • go run . -name Ada -shout

    Flags go before the other arguments

Tests

  • func TestAdd(t *testing.T) { if Add(1, 2) != 3 { t.Errorf("got %d", Add(1, 2)) } }

    A test lives in a _test.go file and starts with Test

  • go test ./...

    Run every test in the module

  • go test -v -run TestAdd

    Run one test and show each result

  • tests := []struct{ in, want string }{{"A", "a"}}; for _, tc := range tests { t.Run(tc.in, func(t *testing.T) { ... }) }

    A table of cases, each as a subtest

  • go test -cover

    Show how much of the code the tests ran

  • go test -coverprofile=cover.out && go tool cover -func=cover.out

    Save coverage and list it per function

  • go test -count=1 ./...

    Run again without the cached result

HTTP service

  • mux := http.NewServeMux()

    A router

  • mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "ok") })

    Handle one method and path

  • r.URL.Query().Get("name")

    Read a query-string value

  • w.Header().Set("Content-Type", "application/json"); json.NewEncoder(w).Encode(v)

    Answer with JSON

  • json.NewDecoder(r.Body).Decode(&item)

    Read a JSON request body

  • http.Error(w, "bad request", http.StatusBadRequest)

    Answer with an error status

  • log.Fatal(http.ListenAndServe(":8080", mux))

    Serve until the program stops

  • httptest.NewRecorder()  httptest.NewRequest("GET", "/healthz", nil)

    Test a handler without opening a port

  • curl -s localhost:8080/healthz

    Try the running service

Cheatsheet for the Go path · Deboistech · All cheatsheets