Last active
May 24, 2016 13:28
-
-
Save codemartial/447ea2f2c9348f0eaab2d31b9b2ccdee to your computer and use it in GitHub Desktop.
Flattening expvars, full example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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