forked from ton-connect/bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.go
More file actions
86 lines (70 loc) · 1.98 KB
/
common.go
File metadata and controls
86 lines (70 loc) · 1.98 KB
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
package main
import (
"net/http"
"net/url"
"strings"
"github.com/realclientip/realclientip-go"
)
type HttpRes struct {
Message string `json:"message,omitempty" example:"status ok"`
StatusCode int `json:"statusCode,omitempty" example:"200"`
}
func HttpResOk() HttpRes {
return HttpRes{
Message: "OK",
StatusCode: http.StatusOK,
}
}
func HttpResError(errMsg string, statusCode int) (int, HttpRes) {
return statusCode, HttpRes{
Message: errMsg,
StatusCode: statusCode,
}
}
func ExtractOrigin(rawURL string) string {
if rawURL == "" {
return ""
}
u, err := url.Parse(rawURL)
if err != nil {
return rawURL
}
if u.Scheme == "" || u.Host == "" {
return rawURL
}
return u.Scheme + "://" + u.Host
}
type realIPExtractor struct {
strategy realclientip.RightmostTrustedRangeStrategy
}
// newRealIPExtractor creates a new realIPExtractor with the given trusted ranges.
func newRealIPExtractor(trustedRanges []string) (*realIPExtractor, error) {
ipNets, err := realclientip.AddressesAndRangesToIPNets(trustedRanges...)
if err != nil {
return nil, err
}
strategy, err := realclientip.NewRightmostTrustedRangeStrategy("X-Forwarded-For", ipNets)
if err != nil {
return nil, err
}
return &realIPExtractor{
strategy: strategy,
}, nil
}
func (e *realIPExtractor) Extract(request *http.Request) string {
headers := request.Header.Clone()
newXForwardedFor := []string{}
oldXForwardedFor := headers.Get("X-Forwarded-For")
if oldXForwardedFor != "" {
newXForwardedFor = append(newXForwardedFor, oldXForwardedFor)
}
newXForwardedFor = append(newXForwardedFor, request.RemoteAddr)
headers.Set("X-Forwarded-For", strings.Join(newXForwardedFor, ", "))
// RightmostTrustedRangeStrategy ignore the second parameter
if ip := e.strategy.ClientIP(headers, ""); ip != "" {
return ip
}
// Fallback: use RemoteAddrStrategy to cleanly extract IP from RemoteAddr
fallbackStrategy := realclientip.RemoteAddrStrategy{}
return fallbackStrategy.ClientIP(nil, request.RemoteAddr)
}