expvar

Guided tour · Errors & Logging · pkg.go.dev →

Expose internal counters and stats as JSON at /debug/vars. Cheap, built-in observability.

Publish variables

Int / Float / String counters

var requests = expvar.NewInt("requests")
var errs = expvar.NewInt("errors")

func handle(w http.ResponseWriter, r *http.Request) {
    requests.Add(1)
}

Map of counters

var byStatus = expvar.NewMap("by_status")
byStatus.Add("200", 1)

Custom Func var

expvar.Publish("uptime", expvar.Func(func() any {
    return time.Since(start).Seconds()
}))

HTTP endpoint

Importing expvar registers /debug/vars on http.DefaultServeMux automatically.

Import for side effect

import _ "expvar"
// then: go http.ListenAndServe(":6060", nil)
// curl localhost:6060/debug/vars