go 26 lines · 1 tab

Admin-only pprof endpoint with basic auth

Leah Thompson Jan 2026
1 tab
package admin

import (
  "net/http"
  "net/http/pprof"
)

func basicAuth(user, pass string, next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    u, p, ok := r.BasicAuth()
    if !ok || u != user || p != pass {
      w.Header().Set("WWW-Authenticate", `Basic realm="pprof"`)
      http.Error(w, "unauthorized", http.StatusUnauthorized)
      return
    }
    next.ServeHTTP(w, r)
  })
}

func Handler(user, pass string) http.Handler {
  mux := http.NewServeMux()
  mux.HandleFunc("/debug/pprof/", pprof.Index)
  mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
  mux.HandleFunc("/debug/pprof/heap", pprof.Handler("heap").ServeHTTP)
  return basicAuth(user, pass, mux)
}
1 file · go Explain with highlit

net/http/pprof is incredibly useful during performance incidents, but it should never be open to the public internet. I register the pprof handlers on a separate mux and wrap them with Basic Auth (or, better, your real auth middleware). The important practice is separation: run pprof on an internal port, bind it to 127.0.0.1 in non-container environments, and gate it in Kubernetes via an internal Service. The code below shows a minimal wrapper that checks credentials, then forwards to the pprof handler. In production, I also add a timeout and a rate limit because profiles can be expensive. With this in place, you can grab CPU/heap profiles safely without turning diagnostics into a security incident.


Related snips

Share this code

Here's the card — post it anywhere.

Admin-only pprof endpoint with basic auth — share card
Link copied