/
canonicalHost.go
104 lines (93 loc) · 2.65 KB
/
canonicalHost.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package dandler
import (
"crypto/tls"
"fmt"
"net/http"
"strings"
)
type canonicalHost struct {
host string
port string
options int
child http.Handler
}
// These constants are to be used with the Canocial Host Handler.
const (
ForceHTTP = 1 << iota // force http as the redirect target
ForceHTTPS // force https as the redirect target
ForceHost // force the given hostname as the redirect target
ForcePort // force a given port for the redirect target
ForceTemporary // Use a 302 for the redirect
)
// CanonicalHost returns a http.Handler that redirects to the canocial host
// based on certain options. 0 may be passed for options if so desired, or provided
// bits can be forced on the client with a redirect.
func CanonicalHost(url string, options int, childHandler http.Handler) http.Handler {
h := canonicalHost{options: options, child: childHandler}
h.host, h.port = h.splitHostPort(url)
return h
}
func (h canonicalHost) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h.checkHostAndPort(r.Host) || h.checkScheme(r.TLS) {
if h.options&ForceTemporary != 0 {
http.Redirect(w, r, h.buildRedirect(r), http.StatusTemporaryRedirect)
} else {
http.Redirect(w, r, h.buildRedirect(r), http.StatusPermanentRedirect)
}
}
h.child.ServeHTTP(w, r)
}
func (h canonicalHost) splitHostPort(url string) (string, string) {
if !strings.Contains(url, ":") {
return url, ""
}
parts := strings.SplitN(url, ":", 2)
return parts[0], parts[1]
}
func (h canonicalHost) checkHostAndPort(url string) bool {
host, port := h.splitHostPort(url)
if h.options&ForceHost != 0 && host != h.host {
return true
}
if h.options&ForcePort != 0 && port != h.port {
return true
}
return false
}
func (h canonicalHost) checkScheme(conn *tls.ConnectionState) bool {
switch {
case h.options&ForceHTTPS != 0 && conn == nil:
return true
case h.options&ForceHTTP != 0 && conn != nil:
return true
default:
return false
}
}
func (h canonicalHost) buildRedirect(r *http.Request) string {
// if host or port is forced, I have to modify the host header
var host, port, scheme string
host, port = h.splitHostPort(r.URL.Host)
if r.TLS == nil {
scheme = "http"
} else {
scheme = "https"
}
// if forcing certain options, change them now
if h.options&ForceHost != 0 {
host = h.host
}
if h.options&ForcePort != 0 {
port = h.port
}
if h.options&ForceHTTP != 0 {
scheme = "http"
}
if h.options&ForceHTTPS != 0 {
scheme = "https"
}
if port == "" {
return fmt.Sprintf("%s://%s/%s", scheme, host, r.RequestURI)
}
return fmt.Sprintf("%s://%s:%s/%s", scheme, host, port, r.RequestURI)
}