forked from cohousing/location
-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
73 lines (65 loc) · 1.29 KB
/
config.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
package location
import (
"net/http"
"net/url"
"strings"
"github.com/gin-gonic/gin"
)
type (
location struct {
scheme string
host string
base string
headers headers
}
headers struct {
scheme string
host string
}
)
func newLocation(config Config) *location {
return &location{
scheme: config.Scheme,
host: config.Host,
base: config.Base,
headers: headers{
scheme: "X-Forwarded-Proto",
host: "X-Forwarded-Host",
},
}
}
func (l *location) applyToContext(c *gin.Context) {
value := new(url.URL)
value.Scheme = l.resolveScheme(c.Request)
value.Host = l.resolveHost(c.Request)
value.Path = l.base
c.Set(key, value)
}
func (l *location) resolveScheme(r *http.Request) string {
switch {
case r.Header.Get(l.headers.scheme) == "https":
return "https"
case r.URL.Scheme == "https":
return "https"
case r.TLS != nil:
return "https"
case strings.HasPrefix(r.Proto, "HTTPS"):
return "https"
default:
return l.scheme
}
}
func (l *location) resolveHost(r *http.Request) (host string) {
switch {
case r.Header.Get(l.headers.host) != "":
return r.Header.Get(l.headers.host)
case r.Header.Get("X-Host") != "":
return r.Header.Get("X-Host")
case r.Host != "":
return r.Host
case r.URL.Host != "":
return r.URL.Host
default:
return l.host
}
}