Go - REST API & Middleware

Beginner 10/10 Teacher 10/10 Architect 10/10
Tip: The capstone Sample REST API composes middleware for logging and JSON helpers.

Handler Composition

func Logging(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
    log.Printf("%s %s", r.Method, r.URL.Path)
    next.ServeHTTP(w, r)
  })
}

Routes

mux := http.NewServeMux()
mux.HandleFunc("/users", usersHandler)
http.ListenAndServe(":8080", Logging(mux))

JSON Helpers

func writeJSON(w http.ResponseWriter, code int, v any){
  w.Header().Set("Content-Type","application/json")
  w.WriteHeader(code)
  json.NewEncoder(w).Encode(v)
}