diff --git a/util/route/route.go b/util/route/route.go index 8d6c2ed71..9dd059320 100644 --- a/util/route/route.go +++ b/util/route/route.go @@ -85,6 +85,13 @@ func (r *Router) Post(path string, h http.HandlerFunc) { r.rtr.POST(r.prefix+path, handle(h)) } +// Redirect takes an absolute path and sends an internal HTTP redirect for it, +// prefixed by the router's path prefix. Note that this method does not include +// functionality for handling relative paths or full URL redirects. +func (r *Router) Redirect(w http.ResponseWriter, req *http.Request, path string, code int) { + http.Redirect(w, req, r.prefix+path, code) +} + // ServeHTTP implements http.Handler. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { r.rtr.ServeHTTP(w, req) diff --git a/util/route/route_test.go b/util/route/route_test.go new file mode 100644 index 000000000..734682e98 --- /dev/null +++ b/util/route/route_test.go @@ -0,0 +1,27 @@ +package route + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestRedirect(t *testing.T) { + router := New().WithPrefix("/test/prefix") + w := httptest.NewRecorder() + r, err := http.NewRequest("GET", "http://localhost:9090/foo", nil) + if err != nil { + t.Fatalf("Error building test request: %s", err) + } + + router.Redirect(w, r, "/some/endpoint", http.StatusFound) + if w.Code != http.StatusFound { + t.Fatalf("Unexpected redirect status code: got %d, want %d", w.Code, http.StatusFound) + } + + want := "/test/prefix/some/endpoint" + got := w.Header()["Location"][0] + if want != got { + t.Fatalf("Unexpected redirect location: got %s, want %s", got, want) + } +} diff --git a/web/web.go b/web/web.go index f04c9794b..8f1c2a6e0 100644 --- a/web/web.go +++ b/web/web.go @@ -160,7 +160,7 @@ func New(st local.Storage, qe *promql.Engine, rm *rules.Manager, status *Prometh instrf := prometheus.InstrumentHandlerFunc router.Get("/", func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, "/graph", http.StatusFound) + router.Redirect(w, r, "/graph", http.StatusFound) }) router.Get("/graph", instrf("graph", h.graph))