-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecure.go
29 lines (26 loc) · 921 Bytes
/
secure.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package httputil
import (
"fmt"
"net/http"
)
// SecureEnforcer ensures HTTPS in environments that provide the X-Forwarded-Proto header.
func SecureEnforcer(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-Forwarded-Proto") == "http" {
http.Redirect(w, r, fmt.Sprintf("https://%s%s", r.Host, r.RequestURI), http.StatusFound)
return
}
h.ServeHTTP(w, r)
})
}
// SecureHostEnforcer ensures HTTPS in environments that provide the
// X-Forwarded-Proto header and also ensures the host is correct.
func SecureHostEnforcer(host string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Host != host || r.Header.Get("X-Forwarded-Proto") == "http" {
http.Redirect(w, r, fmt.Sprintf("https://%s%s", host, r.RequestURI), http.StatusFound)
return
}
h.ServeHTTP(w, r)
})
}