How to Use the expvar Package in Go

Use the expvar package to expose Go variables as JSON at /debug/vars for easy server monitoring.

The expvar package exposes Go variables as JSON at the /debug/vars HTTP endpoint for monitoring. Import the package and use NewInt, NewFloat, NewString, or NewMap to create variables, then update them with Add or Set methods.

import "expvar"

var requests = expvar.NewInt("requests")

func handler(w http.ResponseWriter, r *http.Request) {
    requests.Add(1)
    // Access via http://localhost:8080/debug/vars
}