http.NewServeMux, HandlerFunc, http.Error, and Server timeouts
func NewServeMux() *ServeMux
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
func Error(w ResponseWriter, error string, code int)
type Server struct {
Addr string
Handler Handler
ReadHeaderTimeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
// additional fields omitted
}Route two GET patterns, write a generic error body, and configure header timeouts on a Server that is never started.
| Parameter | Description |
|---|---|
pattern | A ServeMux pattern. GET /ok matches that method and path in Go 1.22 and later, including Go 1.24.0. |
error, code | The plain-text body and HTTP status written by http.Error. The body is sent to the client. |
Returns: NewServeMux returns *ServeMux. Error returns no value. The Handler writes to the ResponseWriter.
Errors
none from Error— http.Error writes a response; it does not return the internal error you chose not to expose.
- The Server.Addr 127.0.0.1:0 is never passed to ListenAndServe in this example.
- Zero ReadTimeout and WriteTimeout mean no timeout, per official documentation, and they do not replace ReadHeaderTimeout.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "ok")
})
mux.HandleFunc("GET /fail", func(w http.ResponseWriter, r *http.Request) {
internal := fmt.Errorf("open /secret/token: permission denied")
_ = internal
http.Error(w, "invalid request", http.StatusBadRequest)
})
req := httptest.NewRequest(http.MethodGet, "https://example.test/ok", nil)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
fmt.Println("ok", rec.Code, rec.Body.String())
req = httptest.NewRequest(http.MethodGet, "https://example.test/fail", nil)
rec = httptest.NewRecorder()
mux.ServeHTTP(rec, req)
fmt.Println("fail", rec.Code, strings.TrimSpace(rec.Body.String()))
s := &http.Server{
Addr: "127.0.0.1:0",
Handler: mux,
ReadHeaderTimeout: time.Second,
}
fmt.Println("header_timeout", s.ReadHeaderTimeout, "read", s.ReadTimeout, "write", s.WriteTimeout)
}Expected output
ok 200 ok
fail 400 invalid request
header_timeout 1s read 0s write 0sRelated: net/http/httptest, errors, net/http (client)