How do I expose pprof endpoints securely in Go?

When developing applications in Go, it's important to monitor the performance of your code. The pprof tool is a powerful built-in profiler that helps you analyze where your program spends its time and memory. However, exposing pprof endpoints without proper security measures can pose risks, particularly in production environments. This guide provides a method for exposing pprof endpoints securely in Go.


// Import necessary packages
package main

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

func main() {
    // Create a new HTTP server
    mux := http.NewServeMux()

    // Set up pprof endpoints but only if in development mode
    if os.Getenv("APP_ENV") == "development" {
        mux.HandleFunc("/debug/pprof/", pprof.Index)
        mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
        mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
        mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
        mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
    }

    // Start the server
    log.Println("Starting server on :8080")
    err := http.ListenAndServe(":8080", mux)
    if err != nil {
        log.Fatal(err)
    }
}
    

Go pprof profiling secure endpoints Go security performance monitoring Go applications HTTP server development environment