diff options
author | Jaime Martinez <jmartinez@gitlab.com> | 2022-04-26 22:54:52 +0300 |
---|---|---|
committer | Jaime Martinez <jmartinez@gitlab.com> | 2022-04-26 22:54:52 +0300 |
commit | 46b4706ea917e4e5018c455d6737893d9426aada (patch) | |
tree | 807f7fbfaae9ad444e74cf37165669246e537312 /internal | |
parent | 4a8a5d61f87e2aa69630ccf4aacef8cf836e934a (diff) | |
parent | cce3706f57ec6424ea7c62ebffd19a3ccbe49c0e (diff) |
Merge branch 'healthcheck/middleware' into 'master'
refactor: move healthcheck middleware early in the pipeline
See merge request gitlab-org/gitlab-pages!616
Diffstat (limited to 'internal')
-rw-r--r-- | internal/healthcheck/middleware.go | 19 | ||||
-rw-r--r-- | internal/healthcheck/middleware_test.go | 50 |
2 files changed, 69 insertions, 0 deletions
diff --git a/internal/healthcheck/middleware.go b/internal/healthcheck/middleware.go new file mode 100644 index 00000000..2ddd35b7 --- /dev/null +++ b/internal/healthcheck/middleware.go @@ -0,0 +1,19 @@ +package healthcheck + +import ( + "net/http" +) + +// NewMiddleware is serving the application status check +func NewMiddleware(handler http.Handler, statusPath string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == statusPath { + w.Header().Set("Cache-Control", "no-store") + w.Write([]byte("success\n")) + + return + } + + handler.ServeHTTP(w, r) + }) +} diff --git a/internal/healthcheck/middleware_test.go b/internal/healthcheck/middleware_test.go new file mode 100644 index 00000000..124bb0ff --- /dev/null +++ b/internal/healthcheck/middleware_test.go @@ -0,0 +1,50 @@ +package healthcheck_test + +import ( + "io" + "net/http" + "testing" + + "github.com/stretchr/testify/require" + + "gitlab.com/gitlab-org/gitlab-pages/internal/config" + "gitlab.com/gitlab-org/gitlab-pages/internal/healthcheck" +) + +func TestHealthCheckMiddleware(t *testing.T) { + tests := map[string]struct { + path string + body string + }{ + "Not a healthcheck request": { + path: "/foo/bar", + body: "Hello from inner handler", + }, + "Healthcheck request": { + path: "/-/healthcheck", + body: "success\n", + }, + } + + cfg := config.Config{ + General: config.General{ + StatusPath: "/-/healthcheck", + }, + } + + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + io.WriteString(w, "Hello from inner handler") + }) + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + middleware := healthcheck.NewMiddleware(handler, cfg.General.StatusPath) + + u := "https://example.com" + tc.path + + require.HTTPStatusCode(t, middleware.ServeHTTP, http.MethodGet, u, nil, http.StatusOK) + require.HTTPBodyContains(t, middleware.ServeHTTP, http.MethodGet, u, nil, tc.body) + }) + } +} |