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

snippet
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())
}