Module lessons (5/5)
Mini-project: an HTTP server
The net/http stdlib package is enough to build a production-ready HTTP server: routing, handlers, middleware, graceful shutdown. No framework required. For typical REST APIs this is the foundation.
Hello world
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello %s", r.URL.Path[1:])
})
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}http.ListenAndServe blocks and only returns on error. nil as the second argument = "use the DefaultServeMux".
The handler signature
All handlers share the same signature:
func(w http.ResponseWriter, r *http.Request)w http.ResponseWriter— output: headers, status code, body.r *http.Request— input: method, URL, headers, body, context.
Typical pattern:
func ping(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK) // optional, defaults to 200
fmt.Fprintln(w, `{"ok":true}`)
}Routing with ServeMux
*http.ServeMux is the base router. Since Go 1.22 it supports patterns with method and path parameters:
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
fmt.Fprintln(w, "user", id)
})
mux.HandleFunc("POST /users", createUser)
http.ListenAndServe(":8080", mux)For more sophisticated routers (groups, integrated middleware, regex) there's chi, gorilla/mux, gin, echo. The stdlib covers 90% of cases.
Middleware as a decorator
A middleware is a function func(http.Handler) http.Handler:
func logMW(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
})
}
http.ListenAndServe(":8080", logMW(mux))To chain them: logMW(authMW(rateLimitMW(mux))). Each middleware decorates the next.
http.Server for fine control
http.ListenAndServe(addr, h) is a shortcut. For timeouts, TLS, and graceful shutdown you need to instantiate http.Server:
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 2 * time.Minute,
}
log.Fatal(srv.ListenAndServe())Graceful shutdown with context
When the process receives SIGINT/SIGTERM, you want to finish in-flight requests before closing:
ctx, stop := signal.NotifyContext(context.Background(),
os.Interrupt, syscall.SIGTERM)
defer stop()
srv := &http.Server{Addr: ":8080", Handler: mux}
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}()
<-ctx.Done() // wait for the signal
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Println("shutdown:", err)
}srv.Shutdown stops accepting new connections and waits for active ones to finish (up to the deadline passed in).
Reading the JSON body
type CreateUserReq struct {
Name string `json:"name"`
}
func createUser(w http.ResponseWriter, r *http.Request) {
var req CreateUserReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// ... use req.Name
w.WriteHeader(http.StatusCreated)
}r.Body is an io.ReadCloser: the server closes it automatically, but json.NewDecoder does not read past the first JSON object (useful for validating input).
Exercises
Registra l'handler hello sulla route '/' usando http.HandleFunc.
Solution available after 3 attempts
Avvia il server su :8080 con http.ListenAndServe e stampa l'errore se non è nil.
Solution available after 3 attempts
Qual è la firma idiomatica di un handler HTTP in Go?
func H(???) { ... }