From da24d729bbb46238214fb2e8a059680a8e45635a Mon Sep 17 00:00:00 2001 From: Stefan Prodan Date: Mon, 20 Aug 2018 11:25:36 +0300 Subject: [PATCH] Add runtime info handler --- pkg/api/info.go | 38 ++++++++++++++++++++++++++++++++++++++ pkg/api/info_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 pkg/api/info.go create mode 100644 pkg/api/info_test.go diff --git a/pkg/api/info.go b/pkg/api/info.go new file mode 100644 index 0000000..e643b96 --- /dev/null +++ b/pkg/api/info.go @@ -0,0 +1,38 @@ +package api + +import ( + "net/http" + + "runtime" + "strconv" + + "github.com/stefanprodan/k8s-podinfo/pkg/version" +) + +func (s *Server) infoHandler(w http.ResponseWriter, r *http.Request) { + data := struct { + Hostname string `json:"hostname"` + Version string `json:"version"` + Revision string `json:"revision"` + Color string `json:"color"` + Message string `json:"message"` + GOOS string `json:"goos"` + GOARCH string `json:"goarch"` + Runtime string `json:"runtime"` + NumGoroutine string `json:"num_goroutine"` + NumCPU string `json:"num_cpu"` + }{ + Hostname: s.config.Hostname, + Version: version.VERSION, + Revision: version.REVISION, + Color: s.config.UIColor, + Message: s.config.UIMessage, + GOOS: runtime.GOOS, + GOARCH: runtime.GOARCH, + Runtime: runtime.Version(), + NumGoroutine: strconv.FormatInt(int64(runtime.NumGoroutine()), 10), + NumCPU: strconv.FormatInt(int64(runtime.NumCPU()), 10), + } + + s.JSONResponse(w, r, data) +} diff --git a/pkg/api/info_test.go b/pkg/api/info_test.go new file mode 100644 index 0000000..c076be9 --- /dev/null +++ b/pkg/api/info_test.go @@ -0,0 +1,35 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "regexp" + "testing" +) + +func TestInfoHandler(t *testing.T) { + req, err := http.NewRequest("GET", "/api/info", nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + srv := NewMockServer() + handler := http.HandlerFunc(srv.infoHandler) + + handler.ServeHTTP(rr, req) + + // Check the status code is what we expect. + if status := rr.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusOK) + } + + // Check the response body is what we expect. + expected := ".*color.*blue.*" + r := regexp.MustCompile(expected) + if !r.MatchString(rr.Body.String()) { + t.Fatalf("handler returned unexpected body:\ngot \n%v \nwant \n%s", + rr.Body.String(), expected) + } +}