The standard library
The packages that already do what you were about to write, including an HTTP server with routing and middleware.
By devskills editorial team · Last updated
The packages you will use most
| Package | What you use it for |
|---|---|
strings, strconv | text handling and number parsing |
time | durations, deadlines, formatting. Read the docs once, properly: the layout string is 2006-01-02 |
slices, maps, cmp | sorting, searching, and containment without loops |
errors, fmt | Is, As, Join, and %w wrapping |
encoding/json | request and response bodies for your web service |
net/http | server and client — see Web services |
database/sql | the database interface — see Databases |
context | cancellation, everywhere |
log/slog | structured logging, stdlib since 1.21 |
os, io, bufio | files, readers, writers |
sync, sync/atomic | mutexes, once, waitgroups, counters |
testing | tests, benchmarks, fuzzing |
crypto/rand | tokens and IDs. Never math/rand for anything security-related. |
Can you build an HTTP server, router and middleware with only the standard library?
Yes. Since Go 1.22, http.ServeMux matches on the method and on path wildcards, so GET /tasks/{id} is a route and r.PathValue("id") reads the parameter. A request with the wrong method gets a 405 automatically. Middleware is just a function that takes an http.Handler and returns one. encoding/json reads and writes the bodies.
The program below wires all three together and calls the handler through net/http/httptest, so it runs anywhere without opening a port. For a real server with timeouts and a graceful shutdown, continue with An HTTP server with no framework and Middleware and graceful shutdown.
package mainimport ( "bytes" "encoding/json" "fmt" "net/http" "net/http/httptest" "strings")// logging is middleware: it takes a handler and returns one that wraps it.func logging(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Println("log:", r.Method, r.URL.Path) next.ServeHTTP(w, r) })}func main() { mux := http.NewServeMux() // Go 1.22+: method and path wildcards in the pattern, read with PathValue. mux.HandleFunc("GET /tasks/{id}", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"id": r.PathValue("id"), "title": "write docs"}) }) mux.HandleFunc("POST /tasks", func(w http.ResponseWriter, r *http.Request) { var in map[string]string if err := json.NewDecoder(r.Body).Decode(&in); err != nil { http.Error(w, "bad json", http.StatusBadRequest) return } w.WriteHeader(http.StatusCreated) fmt.Fprintf(w, "created %q", in["title"]) }) handler := logging(mux) // httptest calls the handler directly, so this runs without opening a port. body, _ := json.Marshal(map[string]string{"title": "ship it"}) for _, req := range []*http.Request{ httptest.NewRequest("GET", "/tasks/42", nil), httptest.NewRequest("POST", "/tasks", bytes.NewReader(body)), httptest.NewRequest("DELETE", "/tasks/42", nil), } { rec := httptest.NewRecorder() handler.ServeHTTP(rec, req) fmt.Println(rec.Code, strings.TrimSpace(rec.Body.String())) }}slices.Sort, slices.Contains, maps.Keys and cmp.Or cover a lot of what people hand-roll.Try it yourself
package mainimport ( "cmp" "fmt" "maps" "slices" "strings")type User struct { Name string Age int}func main() { xs := []int{5, 2, 9, 1} slices.Sort(xs) fmt.Println(xs, slices.Contains(xs, 9), slices.Index(xs, 5), slices.Max(xs)) users := []User{{"Zoe", 30}, {"Adam", 25}} slices.SortFunc(users, func(a, b User) int { return cmp.Compare(a.Name, b.Name) }) fmt.Println(users) m := map[string]int{"b": 2, "a": 1, "c": 3} // maps.Keys returns an iterator, not a slice; slices.Sorted collects it and sorts it. keys := slices.Sorted(maps.Keys(m)) // maps have no order, so sort them fmt.Println(keys) fmt.Println(strings.Fields(" spread out words ")) before, after, _ := strings.Cut("Bearer abc123", " ") fmt.Println(before, "|", after) fmt.Println(strings.EqualFold("Go", "GO"))}- Write a small program using
strings,strconvandsortinstead of hand-rolled loops. - Explain why reaching for the standard library first saves bugs.
- Fix a hand-written helper by replacing it with the stdlib function that already does it.
slices,mapsandcmp(Go 1.21+) replace many hand-written loops.crypto/randfor anything security-related.math/randis predictable.go docreads the whole library offline, source included.- The stdlib source is clear, idiomatic Go. Read it when you are curious.
slices.SortFunc and slices.Contains.Initials(name): return the first letter of each word, in capitals. Words are separated by any amount of spaces. Use strings.Fields and strings.ToUpper. Example: Initials(" rohan kumar patel ") returns "RKP".Tab indents. Press Esc, then Tab, to leave the editor.
- 1Run
go doc net/http.ServeMuxandgo doc -src errors.Is. - 2Find three functions in
stringsyou did not know existed. - 3Read the source of
errors.Isand work out how it walks the chain.