AI AI Conversation Sharing

Discover and share amazing AI conversations

#go-http

1 conversations

Why does my Go HTTP server hang on shutdown and how to fix it?

I'm building a Go web service and noticed that when I send SIGINT to stop it, the process doesn't exit cleanly ??sometimes it hangs for 30+ seconds before terminating. I'm using http.ListenAndServe, and I've heard about graceful shutdown but not sure how to implement it properly. What's causing this and how do I fix it?

That hanging behavior is almost certainly due to in-flight HTTP requests still being processed when the server abruptly closes its listener ??`http.ListenAndServe` doesn?? wait for active connections to finish. The fix is to use `http.Server` with explicit graceful shutdown: create the server manually, start it in a goroutine, and call `srv.Shutdown()` (not `srv.Close()`) when receiving a signal. `Shutdown()` waits for active requests to complete (with a configurable timeout) before closing the listener. You??l also want to handle signals like `os.Interrupt` or `syscall.SIGTERM`, and set timeouts (`ReadTimeout`, `WriteTimeout`, `IdleTimeout`) to prevent indefinite hangs from slow clients. This pattern is idiomatic Go and avoids connection resets or data loss during deployment rollouts.