http.ServeMux
http.ServeMux is Go's URL router. It maps URL patterns to handlers and dispatches incoming requests to the appropriate handler.
Syntax
// Register a route on the default multiplexer
http.HandleFunc("/path", handlerFunc)
// Create a custom ServeMux (recommended)
mux := http.NewServeMux()
mux.HandleFunc("/path", handlerFunc)
// Start the server with a custom ServeMux
http.ListenAndServe(":8080", mux)
Functions and Methods
| Function / Method | Description |
|---|---|
| http.NewServeMux() | Creates a new ServeMux (multiplexer). Use this when running multiple servers or when you need isolated routing. |
| mux.HandleFunc(pattern, handler) | Registers a handler function for the given URL pattern. |
| mux.Handle(pattern, handler) | Registers an object that implements the http.Handler interface for the given URL pattern. |
| http.StripPrefix(prefix, handler) | Strips the specified prefix from the request path before passing it to the next handler. Commonly used when serving static files. |
| http.FileServer(root) | Creates a Handler that serves files from the given directory. |
Sample Code
package main
import (
"fmt"
"log"
"net/http"
)
func homeHandler(w http.ResponseWriter, r *http.Request) {
// ServeMux matches "/" for any path that doesn't match a more specific pattern
// Use r.URL.Path to check the actual request path
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
fmt.Fprintln(w, "Home page")
}
func apiHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, `{"message":"API response"}`)
}
func main() {
// Create a custom ServeMux
mux := http.NewServeMux()
// Register routes
mux.HandleFunc("/", homeHandler)
mux.HandleFunc("/api/", apiHandler)
// Serve static files under /static/
fs := http.FileServer(http.Dir("./static"))
mux.Handle("/static/", http.StripPrefix("/static/", fs))
fmt.Println("Server started: http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}
Notes
Since Go 1.22, the ServeMux pattern syntax has been enhanced to support HTTP method matching (e.g., GET /api/users) and path parameters (e.g., /users/{id}). For older versions, third-party packages such as gorilla/mux or chi are commonly used.
The default pattern "/" matches all paths. Be sure to return a 404 response for unhandled paths to avoid accidentally catching every request. Patterns ending with a slash (e.g., /api/) act as subtree matches and use prefix matching.
If you find any errors or copyright issues, please contact us.