Building a REST API in Go with only the standard library
Part 1 of the shorty series: the HTTP API of a URL shortener using only net/http. Go 1.22+ ServeMux patterns like GET /links/{code}, strict JSON in and out, error mapping, middleware without a framework, timeouts and httptest tests.
Back in 2019 I wrote a Prometheus client for httprouter. I used httprouter then for one boring reason: the standard library router could not match /links/:code or tell GET from POST. Most Go services back then pulled in httprouter, gorilla/mux or Gin just for that.
Go 1.22 fixed it. http.ServeMux now takes a method and wildcards in the pattern, so GET /links/{code} just works. In this blog we will build the HTTP API of shorty, the URL shortener from part 0 of this series, with only net/http, encoding/json and log/slog. No framework.
Level is beginner. You should know basic Go (structs, interfaces, errors) and have Go 1.22 or newer. I used Go 1.27.3 on my Mac. This is part 1, the storage layer (Postgres with pgx and sqlc) is part 2.
The layout
shorty is one module, github.com/fenixara/shorty. The HTTP code lives in its own package and doesn't know about Postgres or Redis, it only talks to an interface.
cmd/shorty/main.go wiring, config, graceful shutdown
internal/httpapi/ routes, handlers, middleware <- this post
internal/links/ business logic (create, resolve, delete)
internal/shortcode/ base62 codes
internal/cache/ Redis
internal/db/ generated by sqlc (next post)
The handlers needs four things from the links package. That is the whole contract:
type LinkService interface {
Create(ctx context.Context, rawURL, code string) (db.Link, error)
Resolve(ctx context.Context, code string) (string, error)
Get(ctx context.Context, code string) (db.Link, error)
Delete(ctx context.Context, code string) error
}
Because it's an interface, the tests at the end can pass a map instead of a database.
Routes with the new ServeMux patterns
Here are all of shorty's routes.
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", s.healthz)
mux.HandleFunc("GET /readyz", s.readyz)
mux.HandleFunc("POST /links", s.createLink)
mux.HandleFunc("GET /links/{code}", s.getLink)
mux.HandleFunc("DELETE /links/{code}", s.deleteLink)
mux.HandleFunc("GET /{code}", s.redirect)
// requestID runs first so the logger and recoverer can use the ID;
// recoverer sits inside the logger so a panic is logged as a 500.
return chain(mux,
requestID,
logRequests(s.log),
recoverer(s.log),
)
}
A pattern is [METHOD ]PATH. {code} matches one path segment and you read it in the handler with r.PathValue("code"). GET also matches HEAD requests, which is what you want for a redirect service.
Now look at GET /{code} next to GET /links/{code} and GET /healthz. A request for /healthz matches both /healthz and /{code}. The old ServeMux would have needed you to think hard about this. The new one has one rule: the most specific pattern wins. /healthz is a literal, so it beats the wildcard. /links/abc has two segments, so it can only match /links/{code}. If two patterns overlap and neither one is more specific, HandleFunc panics when you register them, so you find out at startup instead of in production. I like that a lot.
There's one leftover. GET /links with no code matches /{code} with code = links. That's why links is on the reserved list from part 0, nobody can create a short link called links, so that request is a clean 404.
The 405 surprise
You get 405 Method Not Allowed for free when the path matches but the method doesn't. I wrote a quick probe test to see what comes back and one line surprised me:
PUT /links -> 405 Allow="GET, HEAD, POST"
POST /golang -> 405 Allow="GET, HEAD"
GET / -> 404
PUT /links says GET is allowed. Why? Because /links also matches GET /{code}, so as far as the mux knows, GET /links is a real route. It is harmless here, but it shows the wildcard is wider than it looks. The other thing I noticed is that the 405 body is plain text (Method Not Allowed), not JSON. If your clients need JSON errors for everything, you would have to wrap the mux and check the status. For shorty I left it.
GET / is a 404 because {code} needs a non-empty segment. If you want a handler for exactly /, the pattern is GET /{$}. Plain / without {$} still means "everything", like it always did.
JSON in
Creating a link takes a small JSON body.
type createLinkRequest struct {
URL string `json:"url"`
Code string `json:"code,omitempty"`
}
func (s *Server) createLink(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 8<<10)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var req createLinkRequest
if err := dec.Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
return
}
l, err := s.links.Create(r.Context(), req.URL, req.Code)
if err != nil {
s.handleError(w, r, err)
return
}
w.Header().Set("Location", "/links/"+l.Code)
writeJSON(w, http.StatusCreated, s.toResponse(l))
}
Two lines in there do most of the safety work. MaxBytesReader caps the body at 8 KB, which is plenty for a URL that is at most 2048 characters, so nobody can stream a gigabyte into the decoder. DisallowUnknownFields turns a typo into an error instead of silently ignoring it. If a client sends "colour" they get this back:
{"error":"invalid JSON body: json: unknown field \"colour\""}
I prefer that strictness for a small API. It catches client bugs early. For a public API that has to stay compatible with old clients, you might want the opposite.
JSON out and errors
Two tiny helpers do all the output:
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}
The order matters. Headers must be set before WriteHeader, anything you set after it is ignored. This trips people up a lot, and there is no error, the header just isn't there.
The service layer returns plain Go errors, and one function turns them into status codes:
func (s *Server) handleError(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, links.ErrNotFound):
writeError(w, http.StatusNotFound, "link not found")
case errors.Is(err, links.ErrCodeTaken):
writeError(w, http.StatusConflict, err.Error())
case errors.Is(err, links.ErrInvalidURL),
errors.Is(err, shortcode.ErrTooShort),
errors.Is(err, shortcode.ErrBadChar),
errors.Is(err, shortcode.ErrReserved):
writeError(w, http.StatusUnprocessableEntity, err.Error())
default:
s.log.ErrorContext(r.Context(), "request failed", "err", err, "request_id", RequestIDFrom(r.Context()))
writeError(w, http.StatusInternalServerError, "internal error")
}
}
Known errors get a clear message. Anything else is a 500 with a generic text, and the real error only goes to the log. You never want a Postgres error with table names in it going back to the client.
The redirect handler itself is short. It uses 302 for the reasons in part 0:
func (s *Server) redirect(w http.ResponseWriter, r *http.Request) {
target, err := s.links.Resolve(r.Context(), r.PathValue("code"))
if err != nil {
s.handleError(w, r, err)
return
}
w.Header().Set("Cache-Control", "private, max-age=0")
http.Redirect(w, r, target, http.StatusFound)
}
Middleware without a framework
A middleware in Go is a function that takes a handler and returns a handler. That's it, frameworks just give it a name.
type Middleware func(http.Handler) http.Handler
// chain applies middleware so the first one in the list 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
}
shorty has three. The request ID one reuses an X-Request-Id from the load balancer if there is one, otherwise it makes one, and puts it in the context:
func requestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-Id")
if id == "" || len(id) > 64 {
b := make([]byte, 8)
_, _ = rand.Read(b)
id = hex.EncodeToString(b)
}
w.Header().Set("X-Request-Id", id)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, id)))
})
}
The access log needs the status code, but http.ResponseWriter doesn't tell you what was written. So we wrap it:
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 }
The Unwrap method is easy to forget. http.ResponseController uses it to reach the real writer underneath, for things like flushing or setting a write deadline. Without it, those calls fail on a wrapped writer.
The third one turns a panic into a 500. My first version had it as the outermost middleware, in front of the request ID. Reading it again before I ran the tests, I saw the problem: a panic would be caught before the ID was set, so the error log would have no request ID, and the access log would never see the request at all. Moving it inside the logger fixed both things. The ID is there, and the access log shows the 500. Order of middleware is the kind of thing you only notice when you read the logs.
Health checks
/healthz always says ok, it only proves the process is alive. /readyz pings Postgres and Redis. My first version returned 503 if either was down. Then I thought about what that means behind a load balancer: Redis goes down, every shorty instance says "not ready", the load balancer takes all of them out, and the site is down. But shorty works fine without Redis, just slower. So each check now has a Required flag, only Postgres has it, and Redis being down is reported in the body with a 200. I added a table test for exactly that case.
Server timeouts and shutdown
http.ListenAndServe(":8080", h) has no timeouts at all. A slow client can hold a connection open forever. So main.go builds the server by hand:
srv := &http.Server{
Addr: ":" + cfg.Port,
Handler: httpapi.NewServer(svc, cfg.BaseURL, log, checks).Handler(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
On SIGTERM it calls srv.Shutdown, which stops taking new connections and waits for the running requests. I covered why this matters on ECS in graceful shutdown of a Go HTTP server on ECS Fargate, shorty does the same thing plus one last flush of its click counts.
Testing with httptest
You don't need a running server to test handlers. httptest.NewRecorder is a fake ResponseWriter and the handler is just a function.
func TestLinkLifecycle(t *testing.T) {
h := newTestServer(nil)
rec := do(t, h, "POST", "/links", `{"url":"https://go.dev/","code":"golang"}`)
if rec.Code != http.StatusCreated {
t.Fatalf("create: %d %s", rec.Code, rec.Body)
}
rec = do(t, h, "GET", "/golang", "")
if rec.Code != http.StatusFound || rec.Header().Get("Location") != "https://go.dev/" {
t.Errorf("redirect: %d Location=%q", rec.Code, rec.Header().Get("Location"))
}
}
newTestServer passes a map-backed fake of LinkService, and do is a three line helper around httptest.NewRequest. The full file also checks bad JSON, unknown fields, 405, 409, the panic path and /readyz. Run it with the race detector:
go test -race ./internal/httpapi/
ok github.com/fenixara/shorty/internal/httpapi 1.698s
Trying it with curl
The real server needs Postgres, which is the next post. If you have Docker, the repo's compose file starts everything. Then:
curl -s -X POST localhost:8080/links \
-d '{"url":"https://fenixara.com/creating-a-multi-stage-dockerfile-for-a-golang-web-service/"}'
{"code":"fms9pj6","url":"https://fenixara.com/creating-a-multi-stage-dockerfile-for-a-golang-web-service/","short_url":"http://localhost:8080/fms9pj6","clicks":0,"created_at":"2026-11-19T06:41:15.655438Z"}
The compose stack also loads a few seed links, one of them is golang:
curl -si localhost:8080/golang | head -5
HTTP/1.1 302 Found
Cache-Control: private, max-age=0
Content-Type: text/html; charset=utf-8
Location: https://go.dev/doc/
X-Request-Id: 6236c60772562d4a
And the access log line for that request, from log/slog with the JSON handler:
{"time":"2026-11-19T06:41:15.703415259Z","level":"INFO","msg":"request","method":"GET","path":"/golang","status":302,"duration_ms":1,"request_id":"6236c60772562d4a"}
Compared to Gin, this is a few more lines for the JSON helpers and middleware. In return there is no dependency to upgrade and nothing to learn beyond net/http. For a service this size I wouldn't go back.
Next part puts real data behind LinkService with pgx and sqlc.