This repository has been archived by the owner on Oct 24, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathreverseProxy.go
94 lines (80 loc) · 1.85 KB
/
reverseProxy.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
88
89
90
91
92
93
94
package transaction
import (
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"context"
"github.com/google/uuid"
)
var via string
type Transport struct {
http.RoundTripper
}
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
beginAt := time.Now()
tsReq := NewReq(req)
if _, ok := req.Header["Accept-Encoding"]; ok {
req.Header.Set("Accept-Encoding", "gzip")
}
resp, err = t.RoundTripper.RoundTrip(req)
if err != nil {
return nil, err
}
endAt := time.Now()
if via != "" {
if v := resp.Header.Get("Via"); v == "" {
resp.Header.Set("Via", via)
} else {
resp.Header.Set("Via", v+", "+via)
}
}
{
id, _ := uuid.NewUUID()
t := Tx{
ID: id,
Req: tsReq,
Resp: NewResp(resp),
ClientAddr: req.RemoteAddr,
BeginAt: beginAt,
EndAt: endAt,
}
go TxHub.Add(t)
}
return resp, nil
}
func NewSingleHostReverseProxy(target *url.URL) *httputil.ReverseProxy {
targetQuery := target.RawQuery
director := func(req *http.Request) {
rURL := new(url.URL)
*rURL = *req.URL
rURL.Host = req.Host
if rURL.Scheme == "" {
rURL.Scheme = "http"
}
ctx := context.WithValue(req.Context(), "rawRequestURL", rURL)
*req = *req.WithContext(ctx)
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
req.Host = target.Host
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
}
return &httputil.ReverseProxy{Director: director}
}
func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}