Net HTTP Server Read Write Timeouts

Harden an HTTP server with read, write, idle, and header timeouts so slow or hostile clients cannot pin connections open.

GoResilience

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"log"
	"net/http"
	"time"
)

func newHardenedServer(addr string) *http.Server {
	return &http.Server{
		Addr:              addr,
		ReadHeaderTimeout: 5 * time.Second, // 头部必须快速到达
		ReadTimeout:       10 * time.Second,
		WriteTimeout:      30 * time.Second,
		IdleTimeout:       120 * time.Second,

		MaxHeaderBytes: 1 << 20, // 头部上限 1MiB

		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if r.Method != http.MethodPost {
				w.Header().Set("Allow", http.MethodPost)
				http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
				return
			}
			fmt.Fprintln(w, "accepted")
		}),
	}
}

func main() {
	srv := newHardenedServer(":8080")
	log.Fatal(srv.ListenAndServe())
}

The file, top to bottom

Net HTTP Server Read Write Timeouts keeps everything in the functions newHardenedServer and main.

Putting it to use

The primary signature is func newHardenedServer(addr string) *http.Server

The demo flow inside main is newHardenedServer — run the file to see it end to end.

Core lines

func main() {
	srv := newHardenedServer(":8080")
	log.Fatal(srv.ListenAndServe())
}

Interactive Tools for This Topic

FAQ

How do you run Net HTTP Server Read Write Timeouts?
The runtime alone is enough: execute the file as a complete program.