From 445c9d5da9d7e25959b36224af68c26e874b1db2 Mon Sep 17 00:00:00 2001 From: pawels-optimizely <44238966+pawels-optimizely@users.noreply.github.com> Date: Tue, 22 Oct 2019 14:56:03 -0700 Subject: [PATCH] feat: expose metrics from expvar (#52) * feat: expose metrics from expvar * adding tests for metrics * small changes after PR --- pkg/admin/handlers/admin_entities.go | 6 ++++++ pkg/admin/handlers/admin_entities_test.go | 23 +++++++++++++++++++++++ pkg/admin/router.go | 1 + 3 files changed, 30 insertions(+) diff --git a/pkg/admin/handlers/admin_entities.go b/pkg/admin/handlers/admin_entities.go index 40742feb..9780a842 100644 --- a/pkg/admin/handlers/admin_entities.go +++ b/pkg/admin/handlers/admin_entities.go @@ -18,6 +18,7 @@ package handlers import ( + "expvar" "net/http" "os" @@ -107,3 +108,8 @@ func (a Admin) AppInfoHeader(next http.Handler) http.Handler { } return http.HandlerFunc(fn) } + +// Metrics returns expvar info +func (a Admin) Metrics(w http.ResponseWriter, r *http.Request) { + expvar.Handler().ServeHTTP(w, r) +} diff --git a/pkg/admin/handlers/admin_entities_test.go b/pkg/admin/handlers/admin_entities_test.go index 260e4253..e50da92c 100644 --- a/pkg/admin/handlers/admin_entities_test.go +++ b/pkg/admin/handlers/admin_entities_test.go @@ -18,6 +18,7 @@ package handlers import ( + "encoding/json" "net/http" "net/http/httptest" "testing" @@ -157,3 +158,25 @@ func TestAppInfoHeaderHandler(t *testing.T) { assert.Equal(t, res.Header["Author"], []string{"2"}) assert.Equal(t, res.Header["App-Name"], []string{"3"}) } + +func TestMetrics(t *testing.T) { + + req, _ := http.NewRequest("GET", "/metrics", nil) + + rr := httptest.NewRecorder() + a := NewAdmin("1", "2", "3", nil) + http.HandlerFunc(a.Metrics).ServeHTTP(rr, req) + + assert.Equal(t, http.StatusOK, rr.Code, "Status code differs") + + var expVarMap JSON + err := json.Unmarshal(rr.Body.Bytes(), &expVarMap) + assert.Nil(t, err) + + memStatsMap, ok := expVarMap["memstats"] + assert.True(t, ok) + + assert.Contains(t, memStatsMap, "Alloc") + assert.Contains(t, memStatsMap, "BySize") + assert.Contains(t, memStatsMap, "BuckHashSys") +} diff --git a/pkg/admin/router.go b/pkg/admin/router.go index 32adb06f..255d326f 100644 --- a/pkg/admin/router.go +++ b/pkg/admin/router.go @@ -38,6 +38,7 @@ func NewRouter(srvcs []handlers.HealthChecker) *chi.Mux { r.Get("/health", optlyAdmin.Health) r.Get("/info", optlyAdmin.AppInfo) + r.Get("/metrics", optlyAdmin.Metrics) return r }