-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
87 lines (77 loc) · 2.13 KB
/
http.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
package apirouter
import (
"net"
"net/http"
"net/url"
"strings"
)
// apirouter.HTTP can be used both as a handler function, or as a handler.
var HTTP = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
ctx, err := NewHttp(rw, req)
if err != nil {
res := ctx.errorResponse(err)
res.ServeHTTP(rw, req)
return
}
res, _ := ctx.Response()
res.ServeHTTP(rw, req)
})
type optionsResponder struct {
allowedMethods []string
}
func (o *optionsResponder) Error() string {
return "Options responder"
}
func (o *optionsResponder) getAllowedMethods() string {
if o.allowedMethods == nil {
return "POST, GET, OPTIONS, PUT, DELETE, PATCH"
}
return strings.Join(o.allowedMethods, ", ")
}
func (o *optionsResponder) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// set headers, return no body
rw.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
rw.Header().Set("Access-Control-Max-Age", "86400")
rw.Header().Set("Access-Control-Allow-Methods", o.getAllowedMethods())
rw.WriteHeader(http.StatusNoContent)
}
// GetDomainForRequest will return the domain for a given http.Request, handling cases with redirects
func GetDomainForRequest(req *http.Request) string {
if originalHost := req.Header.Get("Sec-Original-Host"); originalHost != "" {
if host, _, _ := net.SplitHostPort(originalHost); host != "" {
return host
}
return originalHost
}
if req.Host != "" {
host, _, _ := net.SplitHostPort(req.Host)
if host != "" {
return host
}
return req.Host
}
// fallback
return "_default"
}
// GetPrefixForRequest can be used to obtain the prefix for a given request and will
// be able to address the local server directly. It'll handle Sec-Original-Host and
// Sec-Access-Prefix headers
func GetPrefixForRequest(req *http.Request) *url.URL {
u := &url.URL{Host: GetDomainForRequest(req)}
// determine if we got https
if req.TLS == nil {
u.Scheme = "http"
} else {
u.Scheme = "https"
}
// check if we have a prefix
if pfx := req.Header.Get("Sec-Access-Prefix"); pfx != "" {
if !strings.HasPrefix(pfx, "/") {
pfx = "/" + pfx
}
u.Path = pfx
} else {
u.Path = "/"
}
return u
}