-
Notifications
You must be signed in to change notification settings - Fork 342
/
host.go
61 lines (49 loc) · 1.03 KB
/
host.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
package net
import (
"net"
"net/http"
"strings"
)
// HostPatch is used to modify host[:port] string
type HostPatch struct {
// Remove port if present
RemovePort bool
// Remove trailing dot if present
RemoteTrailingDot bool
// Convert to lowercase
ToLower bool
}
func (h *HostPatch) Apply(original string) string {
host, port := original, ""
// avoid net.SplitHostPort for value without port
if strings.IndexByte(original, ':') != -1 {
if sh, sp, err := net.SplitHostPort(original); err == nil {
host, port = sh, sp
}
}
if h.RemovePort {
port = ""
}
if h.RemoteTrailingDot {
last := len(host) - 1
if last >= 0 && host[last] == '.' {
host = host[:last]
}
}
if h.ToLower {
host = strings.ToLower(host)
}
if port != "" {
return net.JoinHostPort(host, port)
} else {
return host
}
}
type HostPatchHandler struct {
Patch HostPatch
Handler http.Handler
}
func (h *HostPatchHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.Host = h.Patch.Apply(r.Host)
h.Handler.ServeHTTP(w, r)
}