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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
