♻️ Improved redirecting middleware configuration

This commit is contained in:
Maxim Lebedev 2023-11-13 09:37:01 +06:00
parent 7f294a1f80
commit aa7cba5e14
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5
1 changed files with 24 additions and 7 deletions

View File

@ -5,13 +5,16 @@ import (
"net/url" "net/url"
) )
type RedirectConfig struct { type (
Skipper Skipper RedirectConfig struct {
URL *url.URL Skipper Skipper
Code int Code int
} }
func Redirect(config RedirectConfig) Interceptor { redirectLogic func(u *url.URL) (url string, ok bool)
)
func Redirect(config RedirectConfig, redirect redirectLogic) Interceptor {
if config.Skipper == nil { if config.Skipper == nil {
config.Skipper = DefaultSkipper config.Skipper = DefaultSkipper
} }
@ -27,6 +30,20 @@ func Redirect(config RedirectConfig) Interceptor {
return return
} }
http.RedirectHandler(config.URL.String(), config.Code).ServeHTTP(w, r) u := &url.URL{
Scheme: "http",
Host: r.Host,
Path: r.RequestURI,
}
if r.TLS != nil {
u.Scheme += "s"
}
if target, ok := redirect(u); ok {
http.RedirectHandler(target, config.Code).ServeHTTP(w, r)
} else {
next(w, r)
}
} }
} }