-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverseproxy.go
233 lines (199 loc) · 5.64 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// Copyright 2018 The yeqown Author. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package proxy
import (
"net"
"net/http"
"github.com/imdario/mergo"
"github.com/valyala/fasthttp"
)
// var _ Proxier = &ReverseProxy{}
// Option . contains option field of ReverseProxy
type Option struct {
OpenBalance bool
Ws []W
Addrs []string
}
// WithBalancer .
func WithBalancer(addrWeights map[string]Weight) Option {
ws := make([]W, 0, len(addrWeights))
addrs := make([]string, 0, len(addrWeights))
for k, v := range addrWeights {
ws = append(ws, v)
addrs = append(addrs, k)
}
return Option{
OpenBalance: true,
Ws: ws,
Addrs: addrs,
}
}
// ReverseProxy reverse handler using fasthttp.HostClient
// TODO: support https config
type ReverseProxy struct {
oldAddr string // old addr to keep old API working as usual
bla IBalancer // balancer
ws []W // weights of clients, releated by idx
clients []*fasthttp.HostClient // clients
opt *Option // opt contains finnally option to open reverseProxy
}
// NewReverseProxy create an ReverseProxy with options
func NewReverseProxy(oldAddr string, opts ...Option) *ReverseProxy {
dstOption := &Option{
OpenBalance: false,
Ws: nil,
Addrs: nil,
}
// merge opts into dstOption
for _, opt := range opts {
if err := mergo.Map(dstOption, opt, mergo.WithOverride); err != nil {
panic(err)
}
}
// fmt.Printf("dst opt=%+v opts=%+v\n", dstOption, opts)
// apply an new object of `ReverseProxy`
proxy := ReverseProxy{
oldAddr: oldAddr,
bla: nil,
// ws: make([]W, 0, 1),
// clients: make([]*fasthttp.HostClient, 0, 1),
opt: dstOption,
}
(&proxy).init()
return &proxy
}
func (p *ReverseProxy) init() {
if p.opt.OpenBalance {
p.oldAddr = ""
p.clients = make([]*fasthttp.HostClient, len(p.opt.Addrs))
p.ws = p.opt.Ws
p.bla = NewBalancer(p.ws)
for idx, addr := range p.opt.Addrs {
p.clients[idx] = &fasthttp.HostClient{Addr: addr}
}
return
}
// not open balancer
p.ws = append(p.ws, Weight(100))
p.bla = nil
p.clients = append(p.clients,
&fasthttp.HostClient{Addr: p.oldAddr})
}
func (p *ReverseProxy) getClient() *fasthttp.HostClient {
if p.clients == nil {
// closed
panic("ReverseProxy has been closed")
}
if p.bla != nil {
// bla has been opened
idx := p.bla.Distribute()
return p.clients[idx]
}
return p.clients[0]
}
// ServeHTTP ReverseProxy to serve
// ref to: https://golang.org/src/net/http/httputil/reverseproxy.go#L169
func (p *ReverseProxy) ServeHTTP(ctx *fasthttp.RequestCtx) {
req := &ctx.Request
res := &ctx.Response
// prepare request(replace headers and some URL host)
if ip, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil {
req.Header.Add("X-Forwarded-For", ip)
}
// to save all response header
// resHeaders := make(map[string]string)
// res.Header.VisitAll(func(k, v []byte) {
// key := string(k)
// value := string(v)
// if val, ok := resHeaders[key]; ok {
// resHeaders[key] = val + "," + value
// }
// resHeaders[key] = value
// })
for _, h := range hopHeaders {
// if h == "Te" && hv == "trailers" {
// continue
// }
req.Header.Del(h)
}
pc := p.getClient()
if debug {
logger.Infof("recv a requets to proxy to: %s", pc.Addr)
}
// assign the host to support virtual hosting, aka shared web hosting (one IP, multiple domains)
req.SetHost(pc.Addr)
if err := pc.Do(req, res); err != nil {
logger.Errorf("could not proxy: %v\n", err)
res.SetStatusCode(http.StatusInternalServerError)
res.SetBody([]byte(err.Error()))
return
}
logger.Debugf("response headers = %s", res.Header.String())
// write response headers
for _, h := range hopHeaders {
res.Header.Del(h)
}
// logger.Debugf("response headers = %s", resHeaders)
// for k, v := range resHeaders {
// res.Header.Set(k, v)
// }
}
// SetClient ...
func (p *ReverseProxy) SetClient(addr string) *ReverseProxy {
for idx := range p.clients {
p.clients[idx].Addr = addr
}
return p
}
// Reset ...
func (p *ReverseProxy) Reset() {
for idx := range p.clients {
p.clients[idx].Addr = ""
}
}
// Close ... clear and release
func (p *ReverseProxy) Close() {
p.clients = nil
p.opt = nil
p.bla = nil
p.ws = nil
p = nil
}
//
//func copyResponse(src *fasthttp.Response, dst *fasthttp.Response) {
// src.CopyTo(dst)
// logger.Debugf("response header=%v", src.Header)
//}
//
//func copyRequest(src *fasthttp.Request, dst *fasthttp.Request) {
// src.CopyTo(dst)
//}
//
//func cloneResponse(src *fasthttp.Response) *fasthttp.Response {
// dst := new(fasthttp.Response)
// copyResponse(src, dst)
// return dst
//}
//
//func cloneRequest(src *fasthttp.Request) *fasthttp.Request {
// dst := new(fasthttp.Request)
// copyRequest(src, dst)
// return dst
//}
// Hop-by-hop headers. These are removed when sent to the backend.
// As of RFC 7230, hop-by-hop headers are required to appear in the
// Connection header field. These are the headers defined by the
// obsoleted RFC 2616 (section 13.5.1) and are used for backward
// compatibility.
var hopHeaders = []string{
"Connection", // Connection
"Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
"Keep-Alive", // Keep-Alive
"Proxy-Authenticate", // Proxy-Authenticate
"Proxy-Authorization", // Proxy-Authorization
"Te", // canonicalized version of "TE"
"Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522
"Transfer-Encoding", // Transfer-Encoding
"Upgrade", // Upgrade
}