Handling HTTP Requests in Go with ServeMux and Handlers
Go's HTTP request processing revolves around two core components: ServeMux for routing and Handlers for response generation.
- ServeMux acts as an HTTP request router, matching incoming requests against registered URL patterns and invoking the corresponding handler
- Handlers implement the
http.Handlerinterface by defining aServeHTTP(http.ResponseWriter, *http.Request)method
package main
import (
"log"
"net/http"
)
func main() {
router := http.NewServeMux()
redirectHandler := http.RedirectHandler("https://example.com", http.StatusTemporaryRedirect)
router.Handle("/old-path", redirectHandler)
log.Println("Server starting on :8080")
http.ListenAndServe(":8080", router)
}
This implementation:
- Creates a new ServeMux instance
- Registers a redircet handler for "/old-path"
- Starts the server on port 8080
Custom Handler Implementation
Here's a time-based handler that formats the current time:
type clockHandler struct {
timeFormat string
}
func (ch *clockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
currentTime := time.Now().Format(ch.timeFormat)
w.Write([]byte("Current time: " + currentTime))
}
Function Handlers
For simpler cases, standard functions can be converted to handlers:
func showTime(w http.ResponseWriter, r *http.Request) {
now := time.Now().Format(time.RFC1123)
w.Write([]byte("Time now: " + now))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/now", showTime)
log.Println("Starting server...")
http.ListenAndServe(":8080", mux)
}
The HandleFunc method provides a concise way to register function handlers.