Web frameworks · Intermediate · 25 min
Build a JSON API with Go's standard library router
By Padding · Updated 18 Nov 2026
Go 1.27.4 · golang:1.27 image (Debian 13)
You will build a small inventory API in Go 1.27 with only the standard library: method and wildcard routes, strict JSON decoding, logging and panic-recovery middleware, a deadline on every request, a graceful shutdown on SIGTERM, and tests written with httptest.
On this page
Since Go 1.22, the standard library's http.ServeMux matches on the HTTP method and on named path segments, so GET /items/{id} is a route on its own and r.PathValue("id") hands you the value. That closed most of the gap that used to send people to a third-party router. Add a few small handler wrappers and Go's built-in JSON and testing packages, and you have an API with no dependencies outside the standard library, which compiles to one binary.
Write your first Go web server covers handlers, a first JSON endpoint and the basic shutdown pattern. This tutorial goes further. You build an inventory API for a small shop, with create, list, read and delete, and make it behave well when things go wrong: bodies with fields the API does not know, a handler that panics, a store that is slow, and a stop signal arriving in the middle of a request. Each of those gets a proof you can see, and the last step pins them down with tests.
The items live in memory, so restarting the server empties them. The store sits behind four methods, and swapping it for a database later changes only that file. You work in a throwaway folder, ~/inventory-api, and delete it at the end.
Step 1 · Create the module and an in-memory store
Create the project and a module. The module name only has to look like an import path; it does not need to exist anywhere:
mkdir -p ~/inventory-api
cd ~/inventory-api
go mod init example.com/inventory-apiThe store keeps items in a map guarded by a sync.RWMutex, because net/http runs every request in its own goroutine and two requests may touch the map at once. Every method takes a context.Context first, the same way a database driver does. The pause method stands in for the time a real database call takes: with latency at zero it returns at once, and when it is set, it waits but gives up as soon as the context is cancelled. You will use that in step 5 to see deadlines work.
cat > store.go <<'GO'
package main
import (
"cmp"
"context"
"errors"
"slices"
"sync"
"time"
)
var errNotFound = errors.New("item not found")
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
Quantity int `json:"quantity"`
}
type Store struct {
mu sync.RWMutex
items map[int]Item
nextID int
latency time.Duration
}
func NewStore(latency time.Duration) *Store {
return &Store{items: make(map[int]Item), nextID: 1, latency: latency}
}
// pause stands in for the round trip to a real database.
// It gives up as soon as ctx is cancelled or its deadline passes.
func (s *Store) pause(ctx context.Context) error {
if s.latency <= 0 {
return ctx.Err()
}
timer := time.NewTimer(s.latency)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (s *Store) List(ctx context.Context) ([]Item, error) {
if err := s.pause(ctx); err != nil {
return nil, err
}
s.mu.RLock()
defer s.mu.RUnlock()
items := make([]Item, 0, len(s.items))
for _, it := range s.items {
items = append(items, it)
}
slices.SortFunc(items, func(a, b Item) int { return cmp.Compare(a.ID, b.ID) })
return items, nil
}
func (s *Store) Get(ctx context.Context, id int) (Item, error) {
if err := s.pause(ctx); err != nil {
return Item{}, err
}
s.mu.RLock()
defer s.mu.RUnlock()
it, ok := s.items[id]
if !ok {
return Item{}, errNotFound
}
return it, nil
}
func (s *Store) Create(ctx context.Context, name string, quantity int) (Item, error) {
if err := s.pause(ctx); err != nil {
return Item{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
it := Item{ID: s.nextID, Name: name, Quantity: quantity}
s.items[it.ID] = it
s.nextID++
return it, nil
}
func (s *Store) Delete(ctx context.Context, id int) error {
if err := s.pause(ctx); err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.items[id]; !ok {
return errNotFound
}
delete(s.items, id)
return nil
}
GOerrNotFound is a sentinel error: handlers compare against it with errors.Is and answer 404, without parsing error text. List sorts by ID because Go deliberately randomises map iteration order, and an API that returns items in a different order on every call is hard to test and to page through.
Check it worked
gofmt -l .
go vet ./...Both commands print nothing. gofmt -l lists files that are not in Go's standard format, and go vet reports suspicious code. There is no main function yet, so there is nothing to run.
Step 2 · Read and write JSON strictly
An API is only as predictable as the input it accepts. json.Decoder is forgiving by default: it ignores fields it does not know, and it stops after the first JSON value, so a body like {"name":"Fan","quantity":1,"price":5} is quietly accepted without its price, and a body with two objects is half read. A client with a typo in a field name gets a success response and wonders why nothing changed.
Create json.go with one helper that writes JSON, one that writes an error in a fixed shape, and one that reads a request body strictly:
cat > json.go <<'GO'
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
)
const maxBodyBytes = 64 << 10 // 64 KiB is plenty for one item
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Println("write response:", err)
}
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
// decodeJSON reads exactly one JSON object into dst and rejects anything else.
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytes)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
return fmt.Errorf("body must be at most %d bytes", tooBig.Limit)
}
if errors.Is(err, io.EOF) {
return errors.New("body must not be empty")
}
return fmt.Errorf("invalid JSON: %v", err)
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return errors.New("body must hold a single JSON object")
}
return nil
}
GOdecodeJSON does four things:
http.MaxBytesReaderstops reading after 64 KiB and makes the server close the connection, so a client cannot make the API read an endless body. The error it returns is an*http.MaxBytesError, whicherrors.Aspicks out.DisallowUnknownFieldsturns an unexpected key into an error that names the key.- An empty body surfaces as
io.EOF, and gets its own clearer message. - The second
Decodecall must hit the end of the body. If it finds another value, the body held more than one object.
Every error the API sends has the same shape, {"error": "..."}, so client code needs one way to read them.
Check it worked
gofmt -l .
go vet ./...Both commands still print nothing.
Step 3 · Route requests by method and path wildcard
Now the handlers. Create handlers.go. Each handler is a method on a small api struct, which holds what the handlers share, the store and a logger, in place of package-level variables:
cat > handlers.go <<'GO'
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
)
type api struct {
store *Store
logger *slog.Logger
}
type createItemRequest struct {
Name string `json:"name"`
Quantity *int `json:"quantity"`
}
func (a *api) health(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (a *api) listItems(w http.ResponseWriter, r *http.Request) {
items, err := a.store.List(r.Context())
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, items)
}
func (a *api) getItem(w http.ResponseWriter, r *http.Request) {
id, ok := itemID(w, r)
if !ok {
return
}
item, err := a.store.Get(r.Context(), id)
if err != nil {
a.fail(w, r, err)
return
}
writeJSON(w, http.StatusOK, item)
}
func (a *api) createItem(w http.ResponseWriter, r *http.Request) {
var in createItemRequest
if err := decodeJSON(w, r, &in); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
in.Name = strings.TrimSpace(in.Name)
switch {
case in.Name == "":
writeError(w, http.StatusUnprocessableEntity, "name is required")
return
case in.Quantity == nil:
writeError(w, http.StatusUnprocessableEntity, "quantity is required")
return
case *in.Quantity < 0:
writeError(w, http.StatusUnprocessableEntity, "quantity must be 0 or more")
return
}
item, err := a.store.Create(r.Context(), in.Name, *in.Quantity)
if err != nil {
a.fail(w, r, err)
return
}
w.Header().Set("Location", fmt.Sprintf("/items/%d", item.ID))
writeJSON(w, http.StatusCreated, item)
}
func (a *api) deleteItem(w http.ResponseWriter, r *http.Request) {
id, ok := itemID(w, r)
if !ok {
return
}
if err := a.store.Delete(r.Context(), id); err != nil {
a.fail(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// itemID reads the {id} wildcard and answers 400 if it is not a positive number.
func itemID(w http.ResponseWriter, r *http.Request) (int, bool) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil || id < 1 {
writeError(w, http.StatusBadRequest, "id must be a positive whole number")
return 0, false
}
return id, true
}
// fail turns a store error into the right status code.
func (a *api) fail(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, errNotFound):
writeError(w, http.StatusNotFound, "item not found")
case errors.Is(err, context.DeadlineExceeded):
writeError(w, http.StatusServiceUnavailable, "the store took too long, try again")
case errors.Is(err, context.Canceled):
a.logger.Info("client went away", "path", r.URL.Path)
default:
a.logger.Error("store error", "err", err)
writeError(w, http.StatusInternalServerError, "internal error")
}
}
GOThree details carry the design:
createItemRequestis a separate type fromItem, so a client cannot set theid; it is an unknown field there anddecodeJSONrejects it.Quantityis a pointer, so a missing quantity (nil) is different from a quantity of0.- Malformed JSON gets
400 Bad Request, while well-formed JSON with invalid values gets422 Unprocessable Content, so a client can tell "I sent garbage" from "I sent the wrong values". failturns store errors into status codes in one place.context.Canceledmeans the client hung up, so there is nobody to answer and the handler only logs it.
Create routes.go, which connects patterns to handlers. Each pattern names a method and a path, and {id} matches one path segment:
cat > routes.go <<'GO'
package main
import (
"log/slog"
"net/http"
"time"
)
func newHandler(store *Store, logger *slog.Logger, timeout time.Duration) http.Handler {
a := &api{store: store, logger: logger}
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", a.health)
mux.HandleFunc("GET /items", a.listItems)
mux.HandleFunc("POST /items", a.createItem)
mux.HandleFunc("GET /items/{id}", a.getItem)
mux.HandleFunc("DELETE /items/{id}", a.deleteItem)
return mux
}
GOThe logger and timeout arguments are not used yet; the next two steps put them to work. Create main.go. It reads its settings from environment variables, with defaults, so you can run the same binary with different settings without editing code:
cat > main.go <<'GO'
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
if err := run(logger); err != nil {
logger.Error("server stopped with an error", "err", err)
os.Exit(1)
}
}
func run(logger *slog.Logger) error {
addr := envOr("ADDR", "127.0.0.1:8081")
latency, err := time.ParseDuration(envOr("STORE_LATENCY", "0s"))
if err != nil {
return err
}
timeout, err := time.ParseDuration(envOr("REQUEST_TIMEOUT", "2s"))
if err != nil {
return err
}
srv := &http.Server{
Addr: addr,
Handler: newHandler(NewStore(latency), logger, timeout),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
serveErr := make(chan error, 1)
go func() {
logger.Info("listening", "addr", addr)
serveErr <- srv.ListenAndServe()
}()
select {
case err := <-serveErr:
return err
case <-ctx.Done():
}
logger.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
return err
}
if err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {
return err
}
logger.Info("stopped")
return nil
}
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
GOADDR sets the listen address, REQUEST_TIMEOUT the deadline for each request, and STORE_LATENCY the pretend database delay. The server timeouts protect it from slow or stalled clients: headers must arrive within 5 seconds, the whole request within 15, and an idle keep-alive connection is closed after 60. With the 64 KiB body cap, 15 seconds is generous enough for a phone on a weak 3G signal or a throttled prepaid bundle to finish an upload, while a client that stalls completely still gets cut off. main.go also catches SIGTERM; step 6 shows what that buys you.
Build the binary and start it in the background, sending its log to server.log. $! holds the process ID of the job you just started, so save it to stop the server later. Building first matters here: go run starts your program as a child process, and a signal sent to go run does not reliably reach it.
go build -o inventory-api .
./inventory-api > server.log 2>&1 &
SERVER_PID=$!Wait a second for it to start. Create two items, then list them, read one, delete it and read it again. -w '%{http_code}\n' makes curl print the status code after the body:
curl -s -i -X POST http://127.0.0.1:8081/items -H 'Content-Type: application/json' -d '{"name":"Solar lamp","quantity":12}'
curl -s -X POST http://127.0.0.1:8081/items -H 'Content-Type: application/json' -d '{"name":"Water filter","quantity":4}'
curl -s http://127.0.0.1:8081/items
curl -s http://127.0.0.1:8081/items/2
curl -s -X DELETE -w '%{http_code}\n' http://127.0.0.1:8081/items/2
curl -s -w '%{http_code}\n' http://127.0.0.1:8081/items/2Then send the API things it should refuse: an unknown field, a missing quantity, an ID that is not a number, and a method no route accepts:
curl -s -w '%{http_code}\n' -X POST http://127.0.0.1:8081/items -d '{"name":"Fan","quantity":1,"price":5}'
curl -s -w '%{http_code}\n' -X POST http://127.0.0.1:8081/items -d '{"name":"Fan"}'
curl -s -w '%{http_code}\n' http://127.0.0.1:8081/items/abc
curl -s -i -X PUT http://127.0.0.1:8081/items/1Stop the server before you change the code. kill sends SIGTERM, and wait returns once the process has exited:
kill "$SERVER_PID"
wait "$SERVER_PID"Check it worked
The first create prints HTTP/1.1 201 Created, a Location: /items/1 header and the body {"id":1,"name":"Solar lamp","quantity":12}. The rest of the first group prints:
{"id":2,"name":"Water filter","quantity":4}
[{"id":1,"name":"Solar lamp","quantity":12},{"id":2,"name":"Water filter","quantity":4}]
{"id":2,"name":"Water filter","quantity":4}
204
{"error":"item not found"}
404In the second group, the unknown field gets 400 with an error that names price, something like {"error":"invalid JSON: json: unknown field \"price\""}. The missing quantity gets {"error":"quantity is required"} and 422, and abc gets 400. The PUT gets HTTP/1.1 405 Method Not Allowed with an Allow header listing the methods that path does accept, DELETE, GET and HEAD. You wrote no code for the 405: the router knows /items/{id} exists for other methods. A GET route also answers HEAD.
Step 4 · Log every request and recover from panics
Middleware in Go is a function that takes a handler and returns a new handler that does something before or after calling the original. No framework is needed: the type is func(http.Handler) http.Handler. Create middleware.go with three of them, and a chain helper that applies them in a readable order:
cat > middleware.go <<'GO'
package main
import (
"context"
"log/slog"
"net/http"
"runtime/debug"
"time"
)
type middleware func(http.Handler) http.Handler
// chain wraps h so that the first middleware listed runs first.
func chain(h http.Handler, mws ...middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
// statusRecorder remembers the status code a handler sends.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(code int) {
s.status = code
s.ResponseWriter.WriteHeader(code)
}
func (s *statusRecorder) Unwrap() http.ResponseWriter {
return s.ResponseWriter
}
func logRequests(logger *slog.Logger) middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
logger.Info("request",
"method", r.Method,
"path", r.URL.Path,
"status", rec.status,
"duration_ms", time.Since(start).Milliseconds(),
)
})
}
}
func recoverPanics(logger *slog.Logger) middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
v := recover()
if v == nil {
return
}
if v == http.ErrAbortHandler {
panic(v)
}
logger.Error("panic", "value", v, "path", r.URL.Path, "stack", string(debug.Stack()))
writeError(w, http.StatusInternalServerError, "internal error")
}()
next.ServeHTTP(w, r)
})
}
}
func withTimeout(d time.Duration) middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), d)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
GOWhat each one does:
logRequestswrites one structured log line per request. A handler never tells you its status code, so the middleware passes the handler astatusRecorderthat notes the code on its way through. TheUnwrapmethod letshttp.ResponseControllerreach the original writer, so features such as flushing still work through the wrapper.recoverPanicscatches a panic in any handler below it, logs the value and stack trace, and answers with the usual JSON error. Without it, the server still survives, becausenet/httprecovers panics itself, but the client sees the connection close with no response at all.http.ErrAbortHandleris the standard library's signal for "abort this response on purpose", so it is passed on untouched.withTimeoutgives each request a context with a deadline. You will see it work in the next step.
Replace routes.go so the router is wrapped. logRequests is listed first, so it is the outermost layer and logs the 500 that recoverPanics writes:
cat > routes.go <<'GO'
package main
import (
"log/slog"
"net/http"
"time"
)
func newHandler(store *Store, logger *slog.Logger, timeout time.Duration) http.Handler {
a := &api{store: store, logger: logger}
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", a.health)
mux.HandleFunc("GET /items", a.listItems)
mux.HandleFunc("POST /items", a.createItem)
mux.HandleFunc("GET /items/{id}", a.getItem)
mux.HandleFunc("DELETE /items/{id}", a.deleteItem)
return chain(mux,
logRequests(logger),
recoverPanics(logger),
withTimeout(timeout),
)
}
GORebuild, start the server on a new port with ADDR, and send three requests:
go build -o inventory-api .
ADDR=127.0.0.1:8082 ./inventory-api > server.log 2>&1 &
SERVER_PID=$!curl -s -X POST http://127.0.0.1:8082/items -H 'Content-Type: application/json' -d '{"name":"Phone charger","quantity":30}'
curl -s -o /dev/null http://127.0.0.1:8082/items/7
curl -s -o /dev/null http://127.0.0.1:8082/healthz
cat server.logCheck it worked
server.log holds one JSON object per line: a listening line first, then one request line for each call. They look something like this, with your own times:
{"time":"2026-11-18T10:02:11.402Z","level":"INFO","msg":"request","method":"POST","path":"/items","status":201,"duration_ms":0}
{"time":"2026-11-18T10:02:11.415Z","level":"INFO","msg":"request","method":"GET","path":"/items/7","status":404,"duration_ms":0}One JSON object per line is what log tools such as Loki, CloudWatch or jq read without extra parsing. The panic handler is hard to trigger by hand without a route that panics on purpose, so step 7 tests it directly.
Step 5 · Put a deadline on every request
A slow dependency is the commonest way an API falls over: requests pile up waiting on it, each holding memory and a connection. withTimeout gives every request two seconds by default. The store's pause method watches the context, so when the deadline passes it returns context.DeadlineExceeded, and fail turns that into 503 Service Unavailable with a message the client can act on. The rule that makes this work is to pass r.Context() into everything a handler calls, all the way down to the database driver.
Stop the server and start it again with a store that takes three seconds, longer than the two-second deadline:
kill "$SERVER_PID"
wait "$SERVER_PID"
STORE_LATENCY=3s ADDR=127.0.0.1:8083 ./inventory-api > server.log 2>&1 &
SERVER_PID=$!Ask for the list and time it. %{time_total} is the time curl spent, in seconds:
curl -s -w '%{http_code} after %{time_total}s\n' http://127.0.0.1:8083/items
curl -s -w '%{http_code} after %{time_total}s\n' http://127.0.0.1:8083/healthzCheck it worked
The first call answers after about two seconds, not three, with {"error":"the store took too long, try again"} and 503. The health check answers at once with {"status":"ok"} and 200, because it never touches the store. The log has a request line for /items with "status":503 and a duration_ms close to 2000.
The deadline only helps code that listens to the context. A handler that calls time.Sleep, or a library call that takes no context, runs to the end regardless.
Step 6 · Shut down without dropping requests
When a deploy or systemctl stop sends SIGTERM, a server that exits at once cuts off every request in flight. main.go already handles this. signal.NotifyContext cancels ctx when SIGTERM or Ctrl+C arrives. The select then moves on, and srv.Shutdown stops accepting new connections and waits up to ten seconds for running requests to finish. ListenAndServe returns http.ErrServerClosed as soon as shutdown starts, which is why run reads serveErr only after Shutdown returns, and treats that one error as normal.
To see it, start the server with a two-second store and a longer deadline, start a request in the background, and send SIGTERM while that request is still waiting:
kill "$SERVER_PID"
wait "$SERVER_PID"
STORE_LATENCY=2s REQUEST_TIMEOUT=5s ADDR=127.0.0.1:8084 ./inventory-api > server.log 2>&1 &
SERVER_PID=$!curl -s -w '%{http_code}\n' http://127.0.0.1:8084/items > in-flight.txt &
CURL_PID=$!
sleep 0.5
kill -TERM "$SERVER_PID"
wait "$CURL_PID"
wait "$SERVER_PID"
cat in-flight.txt
tail -n 3 server.logCheck it worked
in-flight.txt holds [] and 200: the request that was running when the signal arrived got its full answer. The new store is empty, hence the empty list. The last three lines of server.log are, in order, shutting down, the request line for /items with "status":200, and stopped. wait "$SERVER_PID" returns without an error because the program exits with status 0.
If you run the API under systemd, make sure its stop timeout, TimeoutStopSec, stays longer than the ten seconds the code allows for shutdown, so systemd does not kill the process before it finishes.
Step 7 · Test the handlers with httptest
net/http/httptest builds a fake request and records the response, so tests call the whole handler stack, router and middleware included, with no port and no running server. Create handlers_test.go:
cat > handlers_test.go <<'GO'
package main
import (
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
var quietLogger = slog.New(slog.NewTextHandler(io.Discard, nil))
func newTestHandler(latency, timeout time.Duration) http.Handler {
return newHandler(NewStore(latency), quietLogger, timeout)
}
func do(t *testing.T, h http.Handler, method, target, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, target, strings.NewReader(body))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestCreateThenGet(t *testing.T) {
h := newTestHandler(0, time.Second)
rec := do(t, h, http.MethodPost, "/items", `{"name":"Solar lamp","quantity":12}`)
if rec.Code != http.StatusCreated {
t.Fatalf("create: status = %d, body = %s", rec.Code, rec.Body)
}
if got := rec.Header().Get("Location"); got != "/items/1" {
t.Errorf("Location = %q, want /items/1", got)
}
rec = do(t, h, http.MethodGet, "/items/1", "")
var item Item
if err := json.NewDecoder(rec.Body).Decode(&item); err != nil {
t.Fatal(err)
}
want := Item{ID: 1, Name: "Solar lamp", Quantity: 12}
if item != want {
t.Errorf("got %+v, want %+v", item, want)
}
}
func TestStatusCodes(t *testing.T) {
tests := []struct {
name, method, target, body string
want int
}{
{"unknown field", http.MethodPost, "/items", `{"name":"Fan","quantity":1,"price":5}`, http.StatusBadRequest},
{"two objects", http.MethodPost, "/items", `{"name":"Fan","quantity":1}{}`, http.StatusBadRequest},
{"missing quantity", http.MethodPost, "/items", `{"name":"Fan"}`, http.StatusUnprocessableEntity},
{"id not a number", http.MethodGet, "/items/abc", "", http.StatusBadRequest},
{"no such item", http.MethodGet, "/items/99", "", http.StatusNotFound},
{"wrong method", http.MethodPut, "/items/1", "", http.StatusMethodNotAllowed},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := newTestHandler(0, time.Second)
if rec := do(t, h, tt.method, tt.target, tt.body); rec.Code != tt.want {
t.Errorf("status = %d, want %d (body %s)", rec.Code, tt.want, rec.Body)
}
})
}
}
func TestSlowStoreTimesOut(t *testing.T) {
h := newTestHandler(time.Second, 20*time.Millisecond)
start := time.Now()
rec := do(t, h, http.MethodGet, "/items", "")
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", rec.Code)
}
if took := time.Since(start); took > 500*time.Millisecond {
t.Errorf("took %v, the deadline did not stop the store", took)
}
}
func TestPanicBecomes500(t *testing.T) {
boom := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic("something broke")
})
h := chain(boom, recoverPanics(quietLogger))
rec := do(t, h, http.MethodGet, "/", "")
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500", rec.Code)
}
if !strings.Contains(rec.Body.String(), "internal error") {
t.Errorf("body = %s", rec.Body)
}
}
GOTestStatusCodes is a table test: each row is a case, and t.Run gives each one its own name in the output, so a failure says which row broke. TestSlowStoreTimesOut uses a 20-millisecond deadline against a one-second store and also checks how long the call took, which proves the store gave up early instead of finishing late. TestPanicBecomes500 wraps a handler that panics on purpose, the case you could not trigger with curl. Run the tests with the race detector, which reports any unguarded access to the map from two goroutines:
gofmt -l .
go vet ./...
go test -race -v ./...Check it worked
go test prints --- PASS for TestCreateThenGet, each of the six named cases under TestStatusCodes, TestSlowStoreTimesOut and TestPanicBecomes500, then PASS and a line starting ok example.com/inventory-api. To see a test fail, comment out the dec.DisallowUnknownFields() line in json.go and run go test ./... again: the unknown field case fails with status 201. Put the line back afterwards.
If go test -race says the race detector needs cgo, your Go install has no C compiler to hand. Install one (sudo apt install gcc on Ubuntu) or drop -race.
Step 8 · Clean up
The server has already stopped. Remove the project folder. Go itself stays installed:
cd ~
rm -rf ~/inventory-apiNext steps
- Build the same kind of API with a framework and compare the code: build a REST API in Go with Gin.
- Run the binary as a service that restarts on failure and receives
SIGTERMon stop: run an app as a systemd service. - Explore any API from the command line, headers and status codes included: test an API with curl.
- Go back over the basics of handlers and building a binary: write your first Go web server.
Related tutorials
- How to Write and Run Your First Web Server in GoYou will write a web server in Go 1.27 using only the standard library, with path routes, a JSON endpoint, a POST handler, timeouts and a clean shutdown, then test the handlers without opening a port and build the server into one binary.
- Hello World in Go: go mod init, go run and a single binaryYou will install Go 1.27, create a module, run Hello World with go run, build it into one self-contained binary, cross-compile a Windows .exe from Linux and add a --name flag with the flag package.
- Build a REST API in Go with GinYou will build a versioned inventory API with Gin 1.12 on Go 1.27, with validated JSON input, request IDs, one error shape for every failure, release mode and tests, and know what Gin adds over the standard library router.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials