1717package nettyws
1818
1919import (
20+ "context"
2021 "crypto/tls"
22+ "net"
2123 "net/http"
2224
2325 "github.com/go-netty/go-netty"
@@ -35,6 +37,17 @@ const (
3537 MsgBinary
3638)
3739
40+ // Dialer is a means to establish a connection.
41+ type Dialer interface {
42+ // Dial connects to the given address via the proxy.
43+ Dial (network , addr string ) (c net.Conn , err error )
44+ }
45+
46+ // contextDialer dials using a context
47+ type contextDialer interface {
48+ DialContext (ctx context.Context , network , address string ) (net.Conn , error )
49+ }
50+
3851type options struct {
3952 engine netty.Bootstrap
4053 serveMux * http.ServeMux
@@ -50,6 +63,7 @@ type options struct {
5063 compressThreshold int64
5164 requestHeader http.Header
5265 responseHeader http.Header
66+ dialer Dialer
5367}
5468
5569func parseOptions (opt ... Option ) * options {
@@ -78,6 +92,16 @@ func (wso *options) wsOptions() *websocket.Options {
7892 dialer .Header = ws .HandshakeHeaderHTTP (wso .requestHeader )
7993 }
8094
95+ if wso .dialer != nil {
96+ ctxDialer , isCtxDialer := wso .dialer .(contextDialer )
97+ dialer .NetDial = func (ctx context.Context , network , addr string ) (net.Conn , error ) {
98+ if isCtxDialer {
99+ return ctxDialer .DialContext (ctx , network , addr )
100+ }
101+ return wso .dialer .Dial (network , addr )
102+ }
103+ }
104+
81105 var upgrader = ws .DefaultHTTPUpgrader
82106 if wso .responseHeader != nil {
83107 upgrader .Header = wso .responseHeader
@@ -192,3 +216,10 @@ func WithServerHeader(header http.Header) Option {
192216 options .responseHeader = header
193217 }
194218}
219+
220+ // WithDialer specify the client to connect to the network via a dialer.
221+ func WithDialer (dialer Dialer ) Option {
222+ return func (options * options ) {
223+ options .dialer = dialer
224+ }
225+ }
0 commit comments