Skip to main content

What problem it solves

ServeMux solves the problem of mapping incoming HTTP request paths to the correct handler function in a clean, scalable way.

Without ServeMux...

  • Short version: you become the router. Every request hits one function, and you must decide what to do.

Here's a simple example of how to use http.ServeMux to route requests to different handlers:

Using ServeMux

The http.ServeMux is Go's built-in HTTP request multiplexer. It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.

mux := http.NewServeMux()

mux.HandleFunc("/api/news/google", googleNewsHandler)
mux.HandleFunc("/health", healthHandler)

http.ListenAndServe(":8080", mux)

What happens:

  1. Request arrives at :8080
  2. Go asks the mux: “Who handles /api/news/google?”
  3. The mux finds the matching handler
  4. The handler runs

How ServeMux matches routes, Pattern Matching​

  • ServeMux uses prefix matching, not regex.
mux.HandleFunc("/api/", apiHandler)
mux.HandleFunc("/api/news/", newsHandler)
mux.HandleFunc("/", rootHandler)

Default ServeMux​

Go provides a default ServeMux that you can use without explicitly creating one. You can register handlers directly using http.HandleFunc or http.Handle:

http.HandleFunc("/hello", helloHandler)
http.HandleFunc("/goodbye", goodbyeHandler)
http.ListenAndServe(":8080", nil) // nil uses the default ServeMux