Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you build a production-ready HTTP server using Go's standard net/http package?
Go's net/http package provides a production-capable HTTP server out of the box. Unlike Node.js or Python frameworks, you rarely need a third-party framework for basic HTTP serving — the standard library handles routing, TLS, graceful shutdown, and concurrent request handling.
package main import ( "context" "log" "net/http" "os" "os/signal" "syscall" "time" ) func main() { mux := http.NewServeMux() // Register handlers mux.HandleFunc("GET /health", healthHandler) // Go 1.22+ method+path mux.HandleFunc("GET /users/{id}", getUserHandler) mux.HandleFunc("POST /users", createUserHandler) // Apply middleware chain handler := loggingMiddleware(requestIDMiddleware(mux)) srv := &http.Server{ Addr: ":8080", Handler: handler, ReadTimeout: 5 * time.Second, // time to read full request WriteTimeout: 10 * time.Second, // time to write full response IdleTimeout: 120 * time.Second, // keep-alive timeout MaxHeaderBytes: 1 << 20, // 1 MB header limit } // Start server in a goroutine go func() { log.Printf("server listening on %s", srv.Addr) if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("server error: %v", err) } }() // Graceful shutdown on OS signal quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit log.Println("shutting down server...") ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatalf("forced shutdown: %v", err) } log.Println("server stopped") }
Always set timeouts on production HTTP servers. Without them, slow clients can exhaust goroutines: ReadTimeout prevents slow request bodies, WriteTimeout prevents slow response consumption, and IdleTimeout prevents idle keep-alive connections from accumulating.
More Related questions...