Go 1 cheatsheet

Go 1: Code patterns

6 common Go 1 tasks.

Hello world

The smallest runnable Go program.

package main

import "fmt"

func main() {
	fmt.Println("Hello, world!")
}

HTTP server

Start a web server with only the standard library, using method and path patterns in the router.

package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %s!", r.PathValue("name"))
	})
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Handle and wrap errors

Return errors, wrapping them with context so callers can inspect the cause with errors.Is and errors.As.

if err != nil {
	return fmt.Errorf("load config: %w", err)
}

Run goroutines and wait

Start work concurrently and wait for all of it to finish.

var wg sync.WaitGroup
for _, url := range urls {
	wg.Add(1)
	go func() {
		defer wg.Done()
		fetch(url)
	}()
}
wg.Wait()

Set a timeout with context

Cancel an operation if it takes longer than five seconds.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)

Table-driven test

Run many cases through one test function, each as a named subtest.

func TestAdd(t *testing.T) {
	tests := []struct {
		name     string
		a, b, want int
	}{
		{"positive", 1, 2, 3},
		{"zero", 0, 0, 0},
	}
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			if got := Add(tc.a, tc.b); got != tc.want {
				t.Errorf("got %d, want %d", got, tc.want)
			}
		})
	}
}

Was this page helpful?