♻️ 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"
)
type RedirectConfig struct {
Skipper Skipper
URL *url.URL
Code int
}
type (
RedirectConfig struct {
Skipper Skipper
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 {
config.Skipper = DefaultSkipper
}
@ -27,6 +30,20 @@ func Redirect(config RedirectConfig) Interceptor {
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)
}
}
}