-
Notifications
You must be signed in to change notification settings - Fork 12
/
proxy.go
73 lines (61 loc) · 1.66 KB
/
proxy.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
// Copyright 2020 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package http
import (
"net/http"
"net/url"
"regexp"
)
var (
reForwardedHost = regexp.MustCompile(`host=([^,]+)`)
reForwardedProto = regexp.MustCompile(`proto=(https?)`)
)
// GetProxySchemeAndHost extracts the host and used protocol (either HTTP or HTTPS)
// from the given request. If `allowForwarded` is set, the X-Forwarded-Host,
// X-Forwarded-Proto and Forwarded headers will also be checked to
// support proxies.
func GetProxySchemeAndHost(r *http.Request, allowForwarded bool) (scheme, host string) {
if r == nil {
return
}
if r.TLS != nil {
scheme = "https"
} else {
scheme = "http"
}
host = r.Host
if !allowForwarded {
return
}
if h := r.Header.Get("X-Forwarded-Host"); h != "" {
host = h
}
if h := r.Header.Get("X-Forwarded-Proto"); h == "http" || h == "https" {
scheme = h
}
if h := r.Header.Get("Forwarded"); h != "" {
if r := reForwardedHost.FindStringSubmatch(h); len(r) == 2 {
host = r[1]
}
if r := reForwardedProto.FindStringSubmatch(h); len(r) == 2 {
scheme = r[1]
}
}
return
}
// ResolveProxyUrl resolves a URI reference to a URI from
// a URI u and origin [scheme,host] forwarded behind proxy in r.
// ResolveProxyUrl always returns a new URL instance,
// even if the returned URL is identical to either the
// base or reference.
func ResolveProxyUrl(u *url.URL, r *http.Request, allowForwarded bool) *url.URL {
if u == nil {
return nil
}
u2 := *u
scheme, host := GetProxySchemeAndHost(r, allowForwarded)
u2.Scheme = scheme
u2.Host = host
return &u2
}