How to Use the expvar Package for Exposing Metrics

Use the expvar package to define variables and automatically expose them as JSON at /debug/vars for monitoring.

Use the expvar package to define variables like Int, Float, or Map, then import the package to automatically expose them at /debug/vars.

import (
	"expvar"
	"net/http"
)

var requests = expvar.NewInt("requests")

func main() {
	// Increment the counter
	requests.Add(1)
	
	// Start server to expose /debug/vars
	http.ListenAndServe(":8080", nil)
}

Access the metrics by visiting http://localhost:8080/debug/vars in your browser or via curl.