Skip to content

Instantly share code, notes, and snippets.

@codemartial
Last active May 24, 2016 13:28
Show Gist options
  • Save codemartial/447ea2f2c9348f0eaab2d31b9b2ccdee to your computer and use it in GitHub Desktop.
Save codemartial/447ea2f2c9348f0eaab2d31b9b2ccdee to your computer and use it in GitHub Desktop.
Flattening expvars, full example.
package main
import (
"expvar"
"fmt"
"io"
"net/http"
)
func FlattenVar(kv expvar.KeyValue, w io.Writer, prefix string) {
if m, ok := kv.Value.(*expvar.Map); ok { // If Value is an expvar.Map, append its key to prefix and recurse
m.Do(func(kv_ expvar.KeyValue) { FlattenVar(kv_, w, fmt.Sprintf("%s%s.", prefix, kv.Key)) })
} else {
fmt.Fprintf(w, "\"%s%s\": %s\n", prefix, kv.Key, kv.Value)
}
}
func main() {
scalar := expvar.NewInt("scalar")
scalar.Add(42)
emap := expvar.NewMap("foo")
emap.Add("bar", 1)
emap.Add("bar", 2)
emap2 := (&expvar.Map{}).Init()
emap.Set("baz", emap2)
emap2.Add("frob", 1)
http.HandleFunc("/debug/cosmos", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "text/plain")
expvar.Do(func(kv expvar.KeyValue) {
if kv.Key == "memstats" || kv.Key == "cmdline" {
return
}
FlattenVar(kv, w, "")
})
})
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment