Protect diagnostic endpoints
Protect diagnostic endpoints
Diagnostics can expose stack traces, memory details and service topology and may consume significant CPU or memory. Keep them off public routes, use a separate administrative listener with restricted network access, verified authentication and authorization, and limit expensive requests. Importing net/http/pprof registers handlers on DefaultServeMux; use explicit muxes for public and administrative servers.
package main
import ( "fmt" "net/http" "net/http/httptest" "net/http/pprof" "strings")
func main() { public := http.NewServeMux() public.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }) admin := http.NewServeMux() admin.Handle("GET /debug/pprof/goroutine", pprof.Handler("goroutine")) for _, m := range []*http.ServeMux{public, admin} { w := httptest.NewRecorder() m.ServeHTTP(w, httptest.NewRequest("GET", "/debug/pprof/goroutine?debug=1", nil)) fmt.Println(w.Code, strings.Contains(w.Body.String(), "goroutine profile:")) }}The public mux has no profiling route; the admin mux has exactly one. This test invokes handlers in memory, without opening a socket. The admin handler is deliberately not a deployable service. An explicit mux prevents accidental default mux exposure, but does not itself enforce authentication. Never use a nil server Handler for the public listener when importing pprof.
Expected output:
404 false200 trueInject an authorization decision before expensive work
package main
import ( "fmt" "net/http" "net/http/httptest")
func guard(allowed func(*http.Request) bool, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !allowed(r) { http.Error(w, "forbidden", http.StatusForbidden) return } next.ServeHTTP(w, r) })}func main() { calls := 0 next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; w.WriteHeader(204) }) for _, allow := range []bool{false, true} { h := guard(func(*http.Request) bool { return allow }, next) w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest("GET", "/diagnostics", nil)) fmt.Println(w.Code, calls) }}The injected boolean is a test fixture representing a verified decision, not an authentication implementation. Deny before collecting profiles. Production needs credential verification, a default-deny policy, TLS where applicable, auditing and resource limits; a proxy or localhost binding alone is not sufficient access control.
Expected output:
403 0204 1Try it locally
Build a public mux exposing only /health. Confirm health returns 204 and /debug/pprof/ returns 404 even with pprof imported.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reliability and observability 07: Protect diagnostic endpoints
Check the lesson objective before moving on.
Why avoid a nil public server Handler after importing pprof?
Where should authorization run?