Aggregate Counters With The Expvar Package
Register in-process metrics with expvar Ints and Maps, retrieve them by name with Get, and walk every published variable with Do — no metrics library.
Code
package main
import (
"expvar"
"fmt"
)
func main() {
requests := expvar.NewInt("requests")
requests.Add(1)
requests.Add(1)
failures := expvar.NewInt("failures")
failures.Add(1)
// Map 变量按字符串键聚合:每个键自动挂一个 Int 子计数器
counters := expvar.NewMap("counters")
counters.Add("timeout", 2)
counters.Add("refused", 1)
// Get 按名取回已注册变量,类型断言回具体 Var 后继续读写
if v := expvar.Get("failures"); v != nil {
if counter, ok := v.(*expvar.Int); ok {
counter.Add(1)
}
}
// Do 遍历全部已发布变量:Key 是名字,Value 是具体 Var
expvar.Do(func(kv expvar.KeyValue) {
fmt.Printf("%s = %s\n", kv.Key, kv.Value.String())
})
fmt.Println("requests now:", requests.String())
}Where the work happens
The snippet is organized around the function main.
Watch out for
- Zero packages pulled in — the runtime ships every API this code touches.
Putting it to use
Entry signature: func main()
The output carries labels — requests now: — when the file runs.
Core lines
requests := expvar.NewInt("requests")
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Aggregate Counters With The Expvar Package print when run?
- Execute the whole file; each printed line is prefixed with a label like `requests now:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.