Build HTTP and database integrations

Build a Go HTTP Server with a Custom ServeMux and Middleware

Build a small Go HTTP server with a private ServeMux, logging middleware, explicit server configuration, and a health route.

By Niko Minadze3 min read

Editorial illustration for Build a Go HTTP Server with a Custom ServeMux and Middleware

A small Go server needs three pieces connected in the right order: handlers for individual requests, a ServeMux that selects a handler, and an http.Server whose Handler is the mux or a wrapper around it. The key decision is to pass your own mux to the server rather than register routes globally and rely on the default mux.

Create a private mux and register handlers

An http.Handler has one method, ServeHTTP(http.ResponseWriter, *http.Request). The writer receives the response; the request carries information about the incoming call. For a function with that signature, ServeMux.HandleFunc provides a convenient way to register it.

Use /health for a health endpoint that should match that path, not every path beneath it. A pattern without a trailing slash matches the exact path. A pattern such as /health/ also matches paths beginning with that prefix, including /health/details. This distinction matters when a route is meant to be one endpoint rather than a subtree. The ServeMux walkthrough illustrates both forms.

Wrap the mux, then give it to the server

Middleware can accept an http.Handler and return another http.Handler. Its returned handler does work around a call to next.ServeHTTP. In this example, logging runs before the mux dispatches the request and again after the selected handler returns. The health handler does not need to know logging exists.

Save this complete example as main.go:

package main

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

func healthHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "ok")
}

func logRequests(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Printf("started %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r)
        log.Printf("finished %s %s", r.Method, r.URL.Path)
    })
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/health", healthHandler)

    server := &http.Server{
        Addr:           "localhost:8080",
        Handler:        logRequests(mux),
        MaxHeaderBytes: 1 << 20,
    }

    log.Printf("listening at http://%s", server.Addr)
    log.Fatal(server.ListenAndServe())
}

Follow the Handler assignment to see what serves each request. The server calls the handler returned by logRequests. That wrapper calls mux.ServeHTTP; the mux selects healthHandler when the path matches /health. Logging surrounds the mux, not just the health function, so requests for other paths pass through it too.

MaxHeaderBytes is an optional server setting for the maximum request-header size. It is not a request-body limit. The net/http documentation shows Addr, Handler, and MaxHeaderBytes on a custom http.Server, followed by ListenAndServe. Here the address uses localhost:8080 so the example listens on the local machine. The final log.Fatal reports an error returned by ListenAndServe rather than silently discarding it.

This is deliberately different from http.HandleFunc paired with http.ListenAndServe(":8080", nil). Passing a nil handler uses DefaultServeMux, and package-level http.HandleFunc registers routes there. That arrangement works for small examples, including the Go wiki tutorial, but an explicit Handler makes this server's routing dependency visible where the server is constructed.

Run it and check both paths

Start the program in one terminal:

go run main.go

Then request the registered path from another terminal:

curl -i http://localhost:8080/health

Expect a successful response with ok in the body. Now request a path you did not register:

curl -i http://localhost:8080/missing

This second request exercises the mux with an unregistered path. Check the server log for both requests: each passes through the logging wrapper, while only /health reaches healthHandler. If the health request instead fails to connect, check that the program is still running and that its startup log reports localhost:8080. If you later add routes, register them on this same mux before passing logRequests(mux) to the server.

Comments

No comments yet.

Leave a comment

Your comment appears after approval. Plain text only; links stay as text. Line breaks and indentation are kept.

Up to 5,000 characters. No account or email needed.

All articles

Type at least two characters.

Press <kbd>Esc</kbd> to closeOpen the search page