diff options
author | Aliaksandr Valialkin <valyala@gmail.com> | 2016-02-05 16:42:35 +0200 |
---|---|---|
committer | Aliaksandr Valialkin <valyala@gmail.com> | 2016-02-05 16:42:35 +0200 |
commit | e05941507f20b35c391a678b3164f2830e7ca00b (patch) | |
tree | 793492e7d4bc9f2e96d98f99faafb60d80e26502 /fasthttputil | |
parent | fasthttputil: renamed files: pipe -> pipeconns (diff) | |
download | fasthttp-e05941507f20b35c391a678b3164f2830e7ca00b.tar.gz fasthttp-e05941507f20b35c391a678b3164f2830e7ca00b.tar.bz2 fasthttp-e05941507f20b35c391a678b3164f2830e7ca00b.zip |
fasthttputil: added ExpvarHandler for serving variables exported via standard expvar package
Diffstat (limited to 'fasthttputil')
-rw-r--r-- | fasthttputil/doc.go | 2 | ||||
-rw-r--r-- | fasthttputil/expvar.go | 28 | ||||
-rw-r--r-- | fasthttputil/expvar_test.go | 41 |
3 files changed, 71 insertions, 0 deletions
diff --git a/fasthttputil/doc.go b/fasthttputil/doc.go new file mode 100644 index 0000000..9cf69e7 --- /dev/null +++ b/fasthttputil/doc.go @@ -0,0 +1,2 @@ +// Package fasthttputil provides utility functions for fasthttp. +package fasthttputil diff --git a/fasthttputil/expvar.go b/fasthttputil/expvar.go new file mode 100644 index 0000000..b2679a2 --- /dev/null +++ b/fasthttputil/expvar.go @@ -0,0 +1,28 @@ +package fasthttputil + +import ( + "expvar" + "fmt" + + "github.com/valyala/fasthttp" +) + +// ExpvarHandler dumps json representation of expvars to http response. +// +// See https://golang.org/pkg/expvar/ for details. +func ExpvarHandler(ctx *fasthttp.RequestCtx) { + ctx.Response.Reset() + + fmt.Fprintf(ctx, "{\n") + first := true + expvar.Do(func(kv expvar.KeyValue) { + if !first { + fmt.Fprintf(ctx, ",\n") + } + first = false + fmt.Fprintf(ctx, "%q: %s", kv.Key, kv.Value) + }) + fmt.Fprintf(ctx, "\n}\n") + + ctx.SetContentType("application/json; charset=utf-8") +} diff --git a/fasthttputil/expvar_test.go b/fasthttputil/expvar_test.go new file mode 100644 index 0000000..4c409a0 --- /dev/null +++ b/fasthttputil/expvar_test.go @@ -0,0 +1,41 @@ +package fasthttputil + +import ( + "encoding/json" + "expvar" + "testing" + + "github.com/valyala/fasthttp" +) + +func TestExpvarHandler(t *testing.T) { + expvar.Publish("customVar", expvar.Func(func() interface{} { + return "foobar" + })) + + var ctx fasthttp.RequestCtx + + ExpvarHandler(&ctx) + + body := ctx.Response.Body() + + var m map[string]interface{} + if err := json.Unmarshal(body, &m); err != nil { + t.Fatalf("unexpected error: %s", err) + } + + if _, ok := m["cmdline"]; !ok { + t.Fatalf("cannot locate cmdline expvar") + } + if _, ok := m["memstats"]; !ok { + t.Fatalf("cannot locate memstats expvar") + } + + v, ok := m["customVar"] + if !ok { + t.Fatalf("cannot locate customVar") + } + if v != "foobar" { + t.Fatalf("unexpected custom var value: %q. Expecting %q", v, "foobar") + } +} |