-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredirect.go
More file actions
51 lines (47 loc) · 1.49 KB
/
redirect.go
File metadata and controls
51 lines (47 loc) · 1.49 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package api
import (
"net/http"
"strings"
)
// HTTPSRedirect returns middleware that redirects HTTP requests to HTTPS.
func HTTPSRedirect() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.TLS == nil && r.Header.Get("X-Forwarded-Proto") != "https" {
target := "https://" + r.Host + r.URL.RequestURI()
http.Redirect(w, r, target, http.StatusMovedPermanently)
return
}
next.ServeHTTP(w, r)
})
}
}
// TrailingSlash returns middleware that strips trailing slashes and redirects.
func TrailingSlash() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" && strings.HasSuffix(r.URL.Path, "/") {
target := strings.TrimRight(r.URL.Path, "/")
if r.URL.RawQuery != "" {
target += "?" + r.URL.RawQuery
}
http.Redirect(w, r, target, http.StatusMovedPermanently)
return
}
next.ServeHTTP(w, r)
})
}
}
// NonWWWRedirect returns middleware that redirects www subdomain to non-www.
func NonWWWRedirect() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.Host, "www.") {
target := r.URL.Scheme + "://" + strings.TrimPrefix(r.Host, "www.") + r.URL.RequestURI()
http.Redirect(w, r, target, http.StatusMovedPermanently)
return
}
next.ServeHTTP(w, r)
})
}
}