diff options
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) + }) + } +} |