Gin in the wider system · 5 MIN READ
Debug endpoints in Gin: pprof and expvar on a separate admin engine and listener, never on the public router
Mount net/http/pprof and expvar on an admin-only Gin engine behind a network and token guard, and prove with httptest that the public engine does not serve them.
A CPU profile or a goroutine dump from a live process can end an incident in minutes, so production services should be able to produce them. The same endpoints in the wrong hands publish the command line, internal function names and memory statistics, and let anyone start a 30-second CPU profile on demand. The safe arrangement is structural: a second Gin engine that serves only diagnostics, hosted by its own http.Server on an address the internet cannot reach.
gin · A MAP OF THE IDEA
- Build an admin engine
- Guard network and token
- Bind an internal address
- Test public 404 bodies
Useful when
- Profiles are available during an incident without a redeploy.
- The public router cannot leak diagnostics by construction.
Watch out
- A NoRoute fallback to DefaultServeMux leaks pprof with a 404 status.
- pprof.Index only works under the exact /debug/pprof/ prefix.
- Secrets passed as flags appear in cmdline and expvar output.
Implementation & operation cost: A second engine, http.Server and listener with their own budgets and shutdown, plus network policy to keep the port private; profiling itself costs CPU while a profile runs.
What importing net/http/pprof does to the process
The package's init function registers five handlers on http.DefaultServeMux: Index for /debug/pprof/ and the named profiles beneath it, Cmdline, Profile, Symbol and Trace, each with a GET method pattern since Go 1.22. expvar's init does the same for GET /debug/vars and publishes two variables, the command line and runtime memory statistics. The registration happens when the package is linked into the binary, whether you import it with a blank identifier or by name to call pprof.Index, and whether the import is in your code or in a dependency. Each endpoint leaks something: cmdline shows every flag, including any secret passed as one; goroutine?debug=2 prints every stack; profile and trace run the CPU profiler or the execution tracer, with their overhead, for as many seconds as the caller asks. A Gin engine never consults the default mux, so it is safe only as long as nothing else serves that mux.
An admin engine, a guard, and proof that the public engine is clean
The program builds both engines and drives them only with httptest recorders, so no port is opened. It first asks the default mux which pattern would serve the debug paths, then shows the public engine's answers, a leaky variant, and the admin engine behind its guard.
package main
import (
"crypto/subtle"
"encoding/json"
"expvar"
"fmt"
"net/http"
"net/http/httptest"
"net/http/pprof"
"net/netip"
"slices"
"strings"
"github.com/gin-gonic/gin"
)
var notesServed = expvar.NewInt("notes_served")
// newPublic is the internet-facing engine. It never touches http.DefaultServeMux.
func newPublic() *gin.Engine {
r := gin.New()
r.GET("/notes", func(c *gin.Context) {
notesServed.Add(1)
c.JSON(http.StatusOK, gin.H{"items": []string{}})
})
return r
}
// adminOnly admits a caller only from an allowed network AND with the admin token.
func adminOnly(allowed []netip.Prefix, token string) gin.HandlerFunc {
want := []byte("Bearer " + token)
return func(c *gin.Context) {
addr, err := netip.ParseAddr(c.RemoteIP())
if err != nil || !slices.ContainsFunc(allowed, func(p netip.Prefix) bool { return p.Contains(addr.Unmap()) }) {
c.AbortWithStatus(http.StatusForbidden)
return
}
if subtle.ConstantTimeCompare([]byte(c.GetHeader("Authorization")), want) != 1 {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Next()
}
}
// newAdmin is served on a separate, internal-only listener.
func newAdmin(allowed []netip.Prefix, token string) *gin.Engine {
a := gin.New()
a.Use(adminOnly(allowed, token))
pp := a.Group("/debug/pprof")
pp.GET("/", gin.WrapF(pprof.Index))
pp.GET("/cmdline", gin.WrapF(pprof.Cmdline))
pp.GET("/profile", gin.WrapF(pprof.Profile))
pp.GET("/symbol", gin.WrapF(pprof.Symbol))
pp.POST("/symbol", gin.WrapF(pprof.Symbol))
pp.GET("/trace", gin.WrapF(pprof.Trace))
pp.GET("/:profile", gin.WrapF(pprof.Index)) // heap, goroutine, allocs, block, mutex, threadcreate
a.GET("/debug/vars", gin.WrapH(expvar.Handler()))
return a
}
func send(h http.Handler, path, from, auth string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.RemoteAddr = from + ":40000"
if auth != "" {
req.Header.Set("Authorization", auth)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, req)
return w
}
func main() {
gin.SetMode(gin.TestMode)
public := newPublic()
admin := newAdmin([]netip.Prefix{netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("192.0.2.0/24")}, "example-admin-token")
// 1. The import of net/http/pprof already registered handlers on the default mux.
for _, p := range []string{"/debug/pprof/", "/debug/vars"} {
_, pattern := http.DefaultServeMux.Handler(httptest.NewRequest(http.MethodGet, p, nil))
fmt.Printf("default mux %-14s -> pattern %q\n", p, pattern)
}
// 2. The public engine never consults the default mux: debug paths get Gin's 404 body.
for _, p := range []string{"/notes", "/debug/pprof/", "/debug/pprof/heap", "/debug/vars"} {
w := send(public, p, "198.51.100.7", "")
fmt.Printf("public %-17s %d %q\n", p, w.Code, w.Body.String())
}
// 3. A "helpful" fallback to the default mux leaks every side-effect registration,
// and the status still says 404 because Gin preset it before running NoRoute.
leaky := newPublic()
leaky.NoRoute(gin.WrapH(http.DefaultServeMux))
w := send(leaky, "/debug/pprof/", "198.51.100.7", "")
fmt.Printf("leaky %-17s %d %s leaks index=%t\n", "/debug/pprof/", w.Code, w.Header().Get("Content-Type"),
strings.Contains(w.Body.String(), "Types of profiles available"))
// 4. The admin engine: network allow-list first, then the token.
ok := "Bearer example-admin-token"
fmt.Println("admin from 198.51.100.7:", send(admin, "/debug/pprof/", "198.51.100.7", ok).Code)
fmt.Println("admin from 192.0.2.10, no token:", send(admin, "/debug/pprof/", "192.0.2.10", "").Code)
w = send(admin, "/debug/pprof/goroutine?debug=1", "192.0.2.10", ok)
fmt.Println("admin goroutine profile:", w.Code, w.Header().Get("Content-Type"))
w = send(admin, "/debug/vars", "127.0.0.1", ok)
var vars map[string]json.RawMessage
if err := json.Unmarshal(w.Body.Bytes(), &vars); err != nil {
panic(err)
}
_, hasCmdline := vars["cmdline"]
fmt.Printf("admin expvar: %d notes_served=%s cmdline published=%t\n", w.Code, vars["notes_served"], hasCmdline)
}http.DefaultServeMux.Handler reports the patterns GET /debug/pprof/ and GET /debug/vars, registered by the init functions of the two imports. The public engine answers every debug path with Gin's plain 404 body. The leaky engine adds NoRoute(gin.WrapH(http.DefaultServeMux)) and serves the whole pprof index, yet its status is still 404: Gin sets 404 before running NoRoute handlers, and the pprof index never calls WriteHeader. adminOnly checks c.RemoteIP() against the allow-list first, then the bearer token with subtle.ConstantTimeCompare. gin.WrapF adapts each pprof function, gin.WrapH adapts expvar.Handler(), and the decoded expvar JSON shows the custom counter next to the published command line.
A 404 status is not proof
The leaky engine is the failure worth remembering. Someone adds a NoRoute fallback to the default mux so a legacy http.Handle registration keeps working, and every debug endpoint becomes public. A test that only checks for status 404 still passes, because Gin preset the status before the wrapped handler wrote its body. Assert the body and Content-Type too, for every path pprof and expvar register, as the program does. The other ways to serve the default mux are just as quiet: http.ListenAndServe(addr, nil), a metrics server built without a handler, or a second http.Server whose Handler field was left empty. If a service needs standard-library handlers next to Gin, give them a private http.NewServeMux and mount that, never the default one. A review rule that rejects a nil handler argument, plus the public 404-body test, closes both paths.
Mount pprof at exactly /debug/pprof/
pprof.Index chooses a profile by cutting the literal prefix /debug/pprof/ from r.URL.Path. Mount it under /admin/debug/pprof/*any and every profile URL returns the HTML index with status 200, which looks like success and contains no profile. Keep the exact prefix on the admin engine, or wrap the handler in http.StripPrefix and gin.WrapH. In Gin 1.12 the :profile parameter route coexists with the static cmdline, profile, symbol and trace routes, and Gin redirects /debug/pprof to /debug/pprof/ with a 301. Profile and Trace extend the connection's write deadline by the requested seconds through http.ResponseController, which works through Gin because its response writer implements Unwrap. Only one CPU profile can run at a time; a second request gets a 500. The block and mutex profiles stay empty until the program calls runtime.SetBlockProfileRate and runtime.SetMutexProfileFraction.
Two servers in one process
A separate listener is the real boundary; the guard is defense in depth. Bind the admin server to loopback and reach it with kubectl port-forward, or bind it to the Pod address on a port that no public Service or ingress selects and that a NetworkPolicy restricts. The guard uses c.RemoteIP(), not c.ClientIP(), because forwarded headers are client input, as the trusted-proxies lesson explains, and nothing should proxy the admin port anyway. Load the token from configuration rather than a flag, since a flag would appear in the cmdline endpoint it protects, and log every admin request.
public := &http.Server{Addr: ":8080", Handler: newPublic(), ReadHeaderTimeout: 5 * time.Second}
admin := &http.Server{
Addr: "127.0.0.1:6060",
Handler: newAdmin(cfg.AdminNetworks, cfg.AdminToken),
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second, // pprof extends it by ?seconds=
}
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error { return listen(public) })
g.Go(func() error { return listen(admin) })
g.Go(func() error {
<-ctx.Done()
drain, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return errors.Join(public.Shutdown(drain), admin.Shutdown(drain))
})
return g.Wait()Run this fragment in your own environment; listen is a small helper that calls ListenAndServe and treats http.ErrServerClosed as nil. Each engine gets its own http.Server with its own budgets, and the admin WriteTimeout is a floor that pprof raises per request. errgroup ties the two lifetimes together: if either listener fails, ctx is canceled and both servers shut down within one budget, so the process never keeps serving public traffic with its diagnostics gone, or the reverse.
TAKE THIS WITH YOU
Importing pprof or expvar registers handlers on http.DefaultServeMux; serve them only from a separate, guarded admin engine and listener, and test the public engine for a 404 body, not just a 404 status.
Check your understanding
A Gin service imports net/http/pprof. Which statement about the pprof handlers is true?
Go to the source
Progress stays in this browser. No account needed.