-
Notifications
You must be signed in to change notification settings - Fork 11
/
proxy.go
377 lines (330 loc) · 9.72 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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package middleware
import (
"fmt"
"io"
"math/rand"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/webx-top/echo"
)
// TODO: Handle TLS proxy
type (
// ProxyConfig defines the config for Proxy middleware.
ProxyConfig struct {
// Skipper defines a function to skip middleware.
Skipper echo.Skipper `json:"-"`
// Balancer defines a load balancing technique.
// Required.
Balancer ProxyBalancer `json:"-"`
Handler ProxyHandler `json:"-"`
Rewrite RewriteConfig
// Context key to store selected ProxyTarget into context.
// Optional. Default value "target".
ContextKey string
}
// ProxyTarget defines the upstream target.
ProxyTarget struct {
Name string
URL *url.URL
FlushInterval time.Duration
Meta echo.Store
}
ProxyTargeter interface {
GetName() string
GetURL(echo.Context) *url.URL
GetFlushInterval() time.Duration
SetFlushInterval(time.Duration)
GetMeta(echo.Context) echo.Store
}
// ProxyBalancer defines an interface to implement a load balancing technique.
ProxyBalancer interface {
AddTarget(ProxyTargeter) bool
RemoveTarget(string) bool
Next(echo.Context) ProxyTargeter
}
// ProxyHandler defines an interface to implement a proxy handler.
ProxyHandler func(t ProxyTargeter, c echo.Context) error
commonBalancer struct {
targets []ProxyTargeter
mutex sync.RWMutex
}
// RandomBalancer implements a random load balancing technique.
randomBalancer struct {
*commonBalancer
random *rand.Rand
}
// RoundRobinBalancer implements a round-robin load balancing technique.
roundRobinBalancer struct {
*commonBalancer
i uint32
}
)
func (t *ProxyTarget) GetName() string {
return t.Name
}
func (t *ProxyTarget) GetURL(_ echo.Context) *url.URL {
return t.URL
}
func (t *ProxyTarget) GetFlushInterval() time.Duration {
return t.FlushInterval
}
func (t *ProxyTarget) SetFlushInterval(interval time.Duration) {
t.FlushInterval = interval
}
func (t *ProxyTarget) GetMeta(_ echo.Context) echo.Store {
return t.Meta
}
var (
_ ProxyTargeter = &ProxyTarget{}
// DefaultProxyConfig is the default Proxy middleware config.
DefaultProxyConfig = ProxyConfig{
Skipper: echo.DefaultSkipper,
Handler: DefaultProxyHandler,
Rewrite: DefaultRewriteConfig,
ContextKey: "target",
}
// DefaultProxyHandler Proxy Handler
DefaultProxyHandler ProxyHandler = func(t ProxyTargeter, c echo.Context) error {
var key string
switch {
case c.IsWebsocket():
key = `raw`
case c.Header(echo.HeaderAccept) == echo.MIMEEventStream:
key = `sse`
default:
key = `default`
}
if h, ok := DefaultProxyHandlers[key]; ok {
resp := c.Response().StdResponseWriter()
req := c.Request().StdRequest()
h(t, c).ServeHTTP(resp, req)
}
return nil
}
// DefaultProxyHandlers default preset handlers
DefaultProxyHandlers = map[string]func(ProxyTargeter, echo.Context) http.Handler{
`raw`: func(t ProxyTargeter, c echo.Context) http.Handler {
return proxyRaw(t, c)
},
`sse`: func(t ProxyTargeter, c echo.Context) http.Handler {
return proxyHTTPWithFlushInterval(t, c)
},
`default`: func(t ProxyTargeter, c echo.Context) http.Handler {
return proxyHTTP(t, c)
},
}
)
// Server-Sent Events
func proxyHTTPWithFlushInterval(t ProxyTargeter, c echo.Context) http.Handler {
proxy := httputil.NewSingleHostReverseProxy(t.GetURL(c))
proxy.FlushInterval = t.GetFlushInterval()
return proxy
}
// http
func proxyHTTP(t ProxyTargeter, c echo.Context) http.Handler {
return httputil.NewSingleHostReverseProxy(t.GetURL(c))
}
// ProxyHTTPCustomHandler 自定义处理(支持传递body)
func ProxyHTTPCustomHandler(t ProxyTargeter, c echo.Context) http.Handler {
return newSingleHostReverseProxy(t.GetURL(c), c)
}
func newSingleHostReverseProxy(target *url.URL, c echo.Context) *httputil.ReverseProxy {
director := DefaultProxyHTTPDirector(target, c)
return &httputil.ReverseProxy{Director: director}
}
// DefaultProxyHTTPDirector default director
var DefaultProxyHTTPDirector = func(target *url.URL, c echo.Context) func(req *http.Request) {
targetQuery := target.RawQuery
return func(req *http.Request) {
if req.Body == nil {
req.Body = c.Request().Body()
}
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path, req.URL.RawPath = joinURLPath(target, req.URL)
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
}
}
// from net/http/httputil/reverseproxy.go
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
}
// from net/http/httputil/reverseproxy.go
func joinURLPath(a, b *url.URL) (path, rawpath string) {
if a.RawPath == "" && b.RawPath == "" {
return singleJoiningSlash(a.Path, b.Path), ""
}
// Same as singleJoiningSlash, but uses EscapedPath to determine
// whether a slash should be added
apath := a.EscapedPath()
bpath := b.EscapedPath()
aslash := strings.HasSuffix(apath, "/")
bslash := strings.HasPrefix(bpath, "/")
switch {
case aslash && bslash:
return a.Path + b.Path[1:], apath + bpath[1:]
case !aslash && !bslash:
return a.Path + "/" + b.Path, apath + "/" + bpath
}
return a.Path + b.Path, apath + bpath
}
// websocket
func proxyRaw(t ProxyTargeter, c echo.Context) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
in, _, err := w.(http.Hijacker).Hijack()
if err != nil {
c.Error(fmt.Errorf("proxy raw, hijack error=%v, url=%s", t.GetURL(c), err))
return
}
defer in.Close()
out, err := net.Dial("tcp", t.GetURL(c).Host)
if err != nil {
he := echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("proxy raw, dial error=%v, url=%s", t.GetURL(c), err)).SetRaw(err)
c.Error(he)
return
}
defer out.Close()
// Write header
err = r.Write(out)
if err != nil {
he := echo.NewHTTPError(http.StatusBadGateway, fmt.Sprintf("proxy raw, request header copy error=%v, url=%s", t.GetURL(c), err)).SetRaw(err)
c.Error(he)
return
}
errCh := make(chan error, 2)
cp := func(dst io.Writer, src io.Reader) {
_, err = io.Copy(dst, src)
errCh <- err
}
go cp(out, in)
go cp(in, out)
err = <-errCh
if err != nil && err != io.EOF {
c.Logger().Errorf("proxy raw, copy body error=%v, url=%s", t.GetURL(c), err)
}
})
}
// NewRandomBalancer returns a random proxy balancer.
func NewRandomBalancer(targets []ProxyTargeter) ProxyBalancer {
b := &randomBalancer{commonBalancer: new(commonBalancer)}
b.targets = targets
return b
}
// NewRoundRobinBalancer returns a round-robin proxy balancer.
func NewRoundRobinBalancer(targets []ProxyTargeter) ProxyBalancer {
b := &roundRobinBalancer{commonBalancer: new(commonBalancer)}
b.targets = targets
return b
}
// AddTarget adds an upstream target to the list.
func (b *commonBalancer) AddTarget(target ProxyTargeter) bool {
for _, t := range b.targets {
if t.GetName() == target.GetName() {
return false
}
}
b.mutex.Lock()
defer b.mutex.Unlock()
if target.GetFlushInterval() <= 0 {
target.SetFlushInterval(100 * time.Millisecond)
}
b.targets = append(b.targets, target)
return true
}
// RemoveTarget removes an upstream target from the list.
func (b *commonBalancer) RemoveTarget(name string) bool {
b.mutex.Lock()
defer b.mutex.Unlock()
for i, t := range b.targets {
if t.GetName() == name {
b.targets = append(b.targets[:i], b.targets[i+1:]...)
return true
}
}
return false
}
// Next randomly returns an upstream target.
func (b *randomBalancer) Next(c echo.Context) ProxyTargeter {
if b.random == nil {
b.random = rand.New(rand.NewSource(int64(time.Now().Nanosecond())))
}
b.mutex.RLock()
defer b.mutex.RUnlock()
return b.targets[b.random.Intn(len(b.targets))]
}
// Next returns an upstream target using round-robin technique.
func (b *roundRobinBalancer) Next(c echo.Context) ProxyTargeter {
b.i = b.i % uint32(len(b.targets))
t := b.targets[b.i]
atomic.AddUint32(&b.i, 1)
return t
}
// Proxy returns a Proxy middleware.
//
// Proxy middleware forwards the request to upstream server using a configured load balancing technique.
func Proxy(balancer ProxyBalancer) echo.MiddlewareFuncd {
c := DefaultProxyConfig
c.Balancer = balancer
return ProxyWithConfig(c)
}
// ProxyWithConfig returns a Proxy middleware with config.
// See: `Proxy()`
func ProxyWithConfig(config ProxyConfig) echo.MiddlewareFuncd {
// Defaults
if config.Skipper == nil {
config.Skipper = DefaultProxyConfig.Skipper
}
if config.Handler == nil {
config.Handler = DefaultProxyConfig.Handler
}
if config.Balancer == nil {
panic("echo: proxy middleware requires balancer")
}
config.Rewrite.Init()
return func(next echo.Handler) echo.HandlerFunc {
return func(c echo.Context) (err error) {
if config.Skipper(c) {
return next.Handle(c)
}
req := c.Request()
tgt := config.Balancer.Next(c)
if len(config.ContextKey) > 0 {
c.Set(config.ContextKey, tgt)
}
req.URL().SetPath(config.Rewrite.Rewrite(req.URL().Path()))
// Fix header
if len(c.Header(echo.HeaderXRealIP)) == 0 {
req.Header().Set(echo.HeaderXRealIP, c.RealIP())
}
if len(c.Header(echo.HeaderXForwardedProto)) == 0 {
req.Header().Set(echo.HeaderXForwardedProto, c.Scheme())
}
if c.IsWebsocket() && len(c.Header(echo.HeaderXForwardedFor)) == 0 { // For HTTP, it is automatically set by Go HTTP reverse proxy.
req.Header().Set(echo.HeaderXForwardedFor, c.RealIP())
}
return config.Handler(tgt, c)
}
}
}