Dev Skills

The standard library

The packages that already do what you were about to write, including an HTTP server with routing and middleware.

Topic 47 of 101 · 5 min to read · 45 min to build

By devskills editorial team · Last updated

The packages you will use most

PackageWhat you use it for
strings, strconvtext handling and number parsing
timedurations, deadlines, formatting. Read the docs once, properly: the layout string is 2006-01-02
slices, maps, cmpsorting, searching, and containment without loops
errors, fmtIs, As, Join, and %w wrapping
encoding/jsonrequest and response bodies for your web service
net/httpserver and client — see Web services
database/sqlthe database interface — see Databases
contextcancellation, everywhere
log/slogstructured logging, stdlib since 1.21
os, io, bufiofiles, readers, writers
sync, sync/atomicmutexes, once, waitgroups, counters
testingtests, benchmarks, fuzzing
crypto/randtokens 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.

stdlib-http.go
package main
import (
"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()))
}
}
The DELETE request gets 405 Method Not Allowed without any code of yours: the mux knows only GET is registered for that path. Routers such as chi add route groups on top, but routing itself no longer needs one.
Note: A workable rule: write the concrete version. Write it again for the second type. When you find yourself writing it a third time, then generalise. And check the stdlib first. slices.Sort, slices.Contains, maps.Keys and cmp.Or cover a lot of what people hand-roll.

Try it yourself

press Run — this executes on the Go Playground
package main
import (
"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"))
}
The helpers that replace most hand-written loops. Reach for these first. Since Go 1.23, `maps.Keys` and `maps.Values` return an iterator (an `iter.Seq`) instead of a slice, so you pass it to `slices.Sorted` or `slices.Collect`. The Iterators lesson explains how they work.
Check you can now
  • Write a small program using strings, strconv and sort instead 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.
The short version
  • slices, maps and cmp (Go 1.21+) replace many hand-written loops.
  • crypto/rand for anything security-related. math/rand is predictable.
  • go doc reads the whole library offline, source included.
  • The stdlib source is clear, idiomatic Go. Read it when you are curious.
Remember: Check the standard library before you write a helper. It is usually already there.
Build this before moving on
Replace a hand-written sort and a hand-written contains check with slices.SortFunc and slices.Contains.
Coding challenge · checked by tests
Write 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.

Then try these in your own editor
  1. 1Run go doc net/http.ServeMux and go doc -src errors.Is.
  2. 2Find three functions in strings you did not know existed.
  3. 3Read the source of errors.Is and work out how it walks the chain.
Check yourselfTake the Generics and stdlib test