grafana/pkg/middleware/subpath_redirect.go
Torkel Ödegaard 57701fd2f2
ServeFromSubPath: Redirect to URL with subpath when subpath missing (#66724)
* ServeFromSubPath: Redirect to URL with subpath when subpath missing

* Review fixes

* Added tests

* Use constant

* change to useMiddleware

* Update pkg/middleware/subpath_redirect.go

---------

Co-authored-by: Carl Bergquist <carl.bergquist@gmail.com>
2023-04-24 09:55:55 +02:00

27 lines
840 B
Go

package middleware
import (
"fmt"
"net/http"
"strings"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/web"
)
// SubPathRedirect Redirects URLs that are missing the configured subpath to an URL that contains the subpath.
func SubPathRedirect(cfg *setting.Cfg) web.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
// Direct to url with subpath if the request is missing the subpath and is not an API request.
if !strings.HasPrefix(req.RequestURI, cfg.AppSubURL) && !strings.HasPrefix(req.RequestURI, "/api") {
newURL := fmt.Sprintf("%s%s", cfg.AppURL, strings.TrimPrefix(req.RequestURI, "/"))
http.Redirect(rw, req, newURL, http.StatusMovedPermanently)
return
}
next.ServeHTTP(rw, req)
})
}
}