goweb/middleware/invalid_host.go

29 lines
834 B
Go
Raw Normal View History

2018-12-06 15:18:05 +01:00
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)
}
}