goweb/middleware/invalid_host.go
2018-12-06 21:22:30 +01:00

29 lines
834 B
Go

package middleware
import "net/http"
// InvalidHostRedirect returns a middleware that redirects incoming
// requests that do not use the expected host/schemes
func InvalidHostRedirect(expectedHost string, useTLS bool) Middleware {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
invalidScheme := (useTLS && r.TLS == nil) || (!useTLS && r.TLS != nil)
invalidHost := expectedHost != r.Host
if invalidHost || invalidScheme {
if expectedHost != "" {
r.URL.Host = expectedHost
}
if useTLS && r.TLS == nil {
r.URL.Scheme = "https"
} else if !useTLS && r.TLS != nil {
r.URL.Scheme = "http"
}
http.Redirect(w, r, r.URL.String(), http.StatusTemporaryRedirect)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}