diff --git a/web.go b/web.go index 8653c8e..9c4d027 100644 --- a/web.go +++ b/web.go @@ -7,6 +7,7 @@ import ( "net/http" "sync" + "encoding/json" "github.com/Jeffail/gabs" ) @@ -79,6 +80,17 @@ func HealthHandler(w http.ResponseWriter, r *http.Request) { // VarsHandler responds to /varz request and prints config. func VarsHandler(c *context, w http.ResponseWriter, r *http.Request) (int, error) { w.WriteHeader(http.StatusOK) - io.WriteString(w, "Config: "+c.config.String()) + io.WriteString(w, jsonPrettyPrint(c.config.String())) return 200, nil } + +// https://stackoverflow.com/a/36544455/5117259 +func jsonPrettyPrint(in string) string { + var out bytes.Buffer + err := json.Indent(&out, []byte(in), "", "\t") + if err != nil { + return in + } + out.WriteString("\n") + return out.String() +} diff --git a/web_test.go b/web_test.go index e86577d..f82f281 100644 --- a/web_test.go +++ b/web_test.go @@ -236,12 +236,12 @@ func BenchmarkIndexHandler(b *testing.B) { } func TestHealthCheckHandler(t *testing.T) { - Convey("When we GET /zealthz", t, func() { - req, err := http.NewRequest("GET", "/zealthz", nil) + Convey("When we GET /healthz", t, func() { + req, err := http.NewRequest("GET", "/healthz", nil) So(err, ShouldBeNil) req.Host = "sd" - // We create a RegonseRecorder (which satisfies http.RegonseWriter) to record the regonse. + // We create a ResponseWriter (which satisfies http.ResponseWriter) to record the response. rr := httptest.NewRecorder() handler := http.HandlerFunc(HealthHandler) handler.ServeHTTP(rr, req) @@ -271,11 +271,23 @@ func TestVarzHandler(t *testing.T) { Convey("We should get a 200", func() { So(rr.Code, ShouldEqual, http.StatusOK) - conf, err := yaml.YAMLToJSON(c.Bytes()) - So(err, ShouldBeNil) - d, err := yaml.YAMLToJSON(rr.Body.Bytes()) + }) + Convey("It should be valid json", func() { + _, err := yaml.YAMLToJSON(rr.Body.Bytes()) So(err, ShouldBeNil) - So(string(d), ShouldContainSubstring, string(conf)) + }) + Convey("It should equal the config file", func() { + conf, err := yaml.YAMLToJSON(c.Bytes()) + So(err, ShouldBeNil) // sanity check. + + resp, err := yaml.YAMLToJSON(rr.Body.Bytes()) + So(err, ShouldBeNil) // sanity check. + + // We get a nicely formatted response, but when we feed it into YAMLToJSON it collapses our nice + // newlines. As a result, directly comparing the byte arrays here is a nogo. Therefore, we cheat + // and utilize the separately tested jsonPrettyPrint to idempotently indent the JSON and compare that. + // This does not work: "So(resp, ShouldEqual, []byte(jsonPrettyPrint(string(conf))))" + So(jsonPrettyPrint(string(resp)), ShouldEqual, jsonPrettyPrint(string(conf))) }) }) })