net/http (server)

net/http handlers, ServeMux, http.Error, MaxBytesReader, and Server timeouts, tested with httptest.NewRecorder and no listening socket.

モジュールページの本文は現在英語です。

This page is the server side of net/http: Handler, ServeMux, writing a Response, limiting an incoming body, and the timeout fields on Server. The client API is on the net/http (client) page. Examples call ServeHTTP with httptest.NewRequest and httptest.NewRecorder. They do not call ListenAndServe, do not bind a port, and do not send traffic to the public internet.

http.Error writes the supplied text and status to the client. Do not pass a raw internal error, path, or token as that text. ReadHeaderTimeout only bounds reading request headers; official documentation notes that ReadTimeout covers the entire request including the body, and that most users prefer ReadHeaderTimeout so a Handler can decide what is acceptable for the body. Neither field is a substitute for authentication, output filtering, or MaxBytesReader.

Outputs were recorded with Go 1.24.0.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
http.NewServeMux, HandlerFunc, http.Error, and Server timeoutsRoute two GET patterns, write a generic error body, and configure header timeouts on a Server that is never started.
http.MaxBytesReaderReject a 10-byte POST when the limit is 8 bytes, and accept a 4-byte POST. Both run through ServeHTTP and a Recorder.

Handlers, ServeMux, and client-safe errors

A Handler is a value with ServeHTTP(ResponseWriter, *Request). HandlerFunc converts a function to that interface. ServeMux routes by pattern; since Go 1.22 a pattern may include a method, such as GET /ok. The Request that a Handler sees is an incoming server request. Official client documentation says to build those with httptest.NewRequest, not with http.NewRequest.

http.Error sets a text/plain body, a status code, and some safety headers, but it does not end your function for you. The caller should not write further. The message is visible to the client, so this example keeps a generic "invalid request" and discards the internal error value.

A Server value can record Addr, Handler, and timeouts without listening. The example prints ReadHeaderTimeout, ReadTimeout, and WriteTimeout and never starts the server. A Recorder test also does not enforce those deadlines; that limit of Recorder is on the httptest page.

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.

ParameterDescription
patternA ServeMux pattern. GET /ok matches that method and path in Go 1.22 and later, including Go 1.24.0.
error, codeThe 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.
go
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 0s

Related: net/http/httptest, errors, net/http (client)

Official documentation →

Limit incoming bodies with MaxBytesReader

MaxBytesReader wraps an incoming Body and returns a *MaxBytesError once more than n bytes are read. Official documentation says it is intended for this server case, unlike io.LimitReader, and that it may ask the ResponseWriter to close the connection after the limit. The handler still needs to check the read error and decide what status to write.

This example maps any read error to 413 and a generic message. It does not leak the *MaxBytesError text. A size limit is not a timeout, and it is not ReadHeaderTimeout.

http.MaxBytesReader

func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser

Reject a 10-byte POST when the limit is 8 bytes, and accept a 4-byte POST. Both run through ServeHTTP and a Recorder.

ParameterDescription
wThe ResponseWriter, so the implementation can close the connection when the limit is exceeded. A Recorder accepts the call.
r, nThe incoming body and the maximum number of bytes to read.

Returns: An io.ReadCloser. A read past n returns a non-nil *MaxBytesError.

Errors

  • *MaxBytesError — Returned by Read after the limit. The example treats any read error as too large and does not write that error value to the client.
  • io.LimitReader remains the usual cap on a client-side response body, on the client page.
go
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("POST /upload", func(w http.ResponseWriter, r *http.Request) {
		r.Body = http.MaxBytesReader(w, r.Body, 8)
		data, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "invalid request", http.StatusRequestEntityTooLarge)
			return
		}
		fmt.Fprintf(w, "got %d", len(data))
	})

	req := httptest.NewRequest(http.MethodPost, "https://example.test/upload", strings.NewReader("1234567890"))
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	fmt.Println("big", rec.Code, strings.TrimSpace(rec.Body.String()))

	req = httptest.NewRequest(http.MethodPost, "https://example.test/upload", strings.NewReader("1234"))
	rec = httptest.NewRecorder()
	mux.ServeHTTP(rec, req)
	fmt.Println("small", rec.Code, rec.Body.String())
}

Expected output

big 413 invalid request
small 200 got 4

Related: io.LimitReader, mime/multipart

Official documentation →