liveBook · Manning

Http.ServeMux

As explained in Learn Go with Pocket-Sized Projects

ServeMux is the net/http request multiplexer that matches requests to registered handlers.

A single handler is awkward when an HTTP service needs several endpoints. `http.ServeMux` routes requests by URL to registered handlers. Its `ServeHTTP` method makes it an `http.Handler`, so it can be passed to `http.ListenAndServe`. section 8.2.1

Listing 8.4 internal/handlers/router.go: Handler to URL association
package handlers

import (
    "net/http"

    "learngo-pockets/httpgordle/internal/api"
    "learngo-pockets/httpgordle/internal/newgame"
)

// Mux creates a multiplexer with all the endpoints for our service.
func Mux() *http.ServeMux {
    mux := http.NewServeMux()
    mux.HandleFunc(api.NewGameRoute, newgame.Handle) #1
    return mux
}

Create a mux in one function, register `/games` with `HandleFunc`, and return it for use by the server. section 8.2.1

A path-only registration leaves the `/games` handler to reject non-POST requests; the example returns `405 Method Not Allowed` for GET. A later router registers a method-and-path pattern instead. Keep route setup together as endpoints are added. section 8.2.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains construction, registration, and server integration, then shows method handling without exploring matching internals.
Examples
Uses a `/games` creation endpoint, router listings, and curl requests showing GET rejection and POST success.
What it assumes
Assumes Go functions and HTTP requests while introducing the `http.Handler` interface and mux construction.
What you can do after
Build it from scratch with `http.NewServeMux`, register a handler, and pass the mux to `http.ListenAndServe`.
How it connects
Connects `http.Handler`, `HandleFunc`, `ListenAndServe`, URL routing, and HTTP methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.