forked from yeqown/fasthttp-reverse-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws_reverseporxy_option.go
97 lines (78 loc) · 2.41 KB
/
ws_reverseporxy_option.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
package proxy
import (
"errors"
"net/http"
"net/url"
"github.com/fasthttp/websocket"
"github.com/valyala/fasthttp"
)
// OptionWS to define all options to reverse web socket proxy.
type OptionWS interface {
apply(o *buildOptionWS)
}
type funcBuildOptionWS struct {
f func(o *buildOptionWS)
}
func newFuncBuildOptionWS(f func(o *buildOptionWS)) funcBuildOptionWS { return funcBuildOptionWS{f: f} }
func (fb funcBuildOptionWS) apply(o *buildOptionWS) { fb.f(o) }
type forwardHeaderHandler func(ctx *fasthttp.RequestCtx) (forwardHeader http.Header)
// buildOptionWS is Option for WS reverse-proxy
type buildOptionWS struct {
// target indicates which backend server to proxy.
target *url.URL
// fn is forwardHeaderHandler which allows users customize themselves' forward headers
// to be proxied to backend server.
fn forwardHeaderHandler
// dialer contains options for connecting to the backend WebSocket server.
// If nil, DefaultDialer is used.
dialer *websocket.Dialer
// upgrader specifies the parameters for upgrading a incoming HTTP
// connection to a WebSocket connection. If nil, DefaultUpgrader is used.
upgrader *websocket.FastHTTPUpgrader
}
func (o *buildOptionWS) validate() error {
if o == nil {
return errors.New("option is nil")
}
if o.target == nil {
return errors.New("target is nil")
}
return nil
}
func defaultBuildOptionWS() *buildOptionWS {
return &buildOptionWS{
target: nil,
fn: nil,
dialer: nil,
upgrader: nil,
}
}
// WithURL_OptionWS specify the url to backend websocket server.
// WithURL_OptionWS("ws://YOUR_WEBSOCKET_HOST:PORT/AND/PATH")
func WithURL_OptionWS(u string) OptionWS {
return newFuncBuildOptionWS(func(o *buildOptionWS) {
URL, err := url.Parse(u)
if err != nil {
panic(err)
}
o.target = URL
})
}
// WithDialer_OptionWS use specified dialer
func WithDialer_OptionWS(dialer *websocket.Dialer) OptionWS {
return newFuncBuildOptionWS(func(o *buildOptionWS) {
o.dialer = dialer
})
}
// WithUpgrader_OptionWS use specified upgrader.
func WithUpgrader_OptionWS(upgrader *websocket.FastHTTPUpgrader) OptionWS {
return newFuncBuildOptionWS(func(o *buildOptionWS) {
o.upgrader = upgrader
})
}
// WithForwardHeadersHandlers_OptionWS allows users to customize forward headers.
func WithForwardHeadersHandlers_OptionWS(handler forwardHeaderHandler) OptionWS {
return newFuncBuildOptionWS(func(o *buildOptionWS) {
o.fn = handler
})
}