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.
Code
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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
FAQ
- How do you run Net HTTP Server Read Write Timeouts?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.