How to Fix Go HTTP Server Timeout Configuration Errors
In this tutorial, you'll learn about How to Fix Go HTTP Server Timeout Configuration Errors. We cover key concepts, practical examples, and best practices.
Go HTTP server timeout errors occur when the server does not configure read, write, or idle timeouts, allowing slow clients to hold connections open indefinitely and exhaust server resources.
Quick Fix
Wrong
http.HandleFunc("/api", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
No timeouts are set. A slow client can hold a connection open indefinitely, exhausting goroutines and file descriptors.
Right
srv := &http.Server{
Addr: ":8080",
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
}
http.HandleFunc("/api", handler)
log.Fatal(srv.ListenAndServe())
Fix for streaming endpoints
func streamingHandler(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", http.StatusInternalServerError)
return
}
for i := 0; i < 10; i++ {
fmt.Fprintf(w, "data %d\n", i)
flusher.Flush()
time.Sleep(1 * time.Second)
}
}
srv := &http.Server{
Addr: ":8080",
ReadTimeout: 5 * time.Second,
WriteTimeout: 0, // disable for streaming
IdleTimeout: 30 * time.Second,
}
Fix for request cancellation
func handler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
select {
case <-time.After(10 * time.Second):
fmt.Fprintln(w, "done")
case <-ctx.Done():
http.Error(w, "request cancelled", http.StatusRequestTimeout)
}
}
Prevention
- Always set
ReadTimeout,WriteTimeout, andIdleTimeouton production servers. - Set
ReadHeaderTimeoutto prevent slow header attacks. - Use
http.TimeoutHandleras a middleware wrapper for individual handlers. - Check
r.Context().Done()in long-running handlers. - Monitor connection counts and goroutine growth.
DodaTech Tools
Doda Browser's Go HTTP profiler shows request durations, timeout violations, and connection pool states. DodaZIP archives server logs with timing data. Durga Antivirus Pro detects slowloris-style attacks against servers with missing timeouts.
Common Mistakes with http server timeout
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro