/
handler_options.go
68 lines (56 loc) · 2.42 KB
/
handler_options.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
package uwebsocket
import (
"context"
"net/http"
"github.com/dunv/uhttp"
)
type HandlerOption interface {
apply(*handlerOptions)
}
type handlerOptions struct {
uhttpHandler uhttp.Handler
clientAttributes *func(hub *WebSocketHub, r *http.Request) (*ClientAttributes, error)
welcomeMessages *func(hub *WebSocketHub, clientGuid string, clientAttributes *ClientAttributes, r *http.Request, ctx context.Context) ([][]byte, error)
onConnect *func(hub *WebSocketHub, clientGuid string, clientAttributes *ClientAttributes, r *http.Request, ctx context.Context)
onError *func(hub *WebSocketHub, clientGuid string, clientAttributes *ClientAttributes, r *http.Request, err error, ctx context.Context)
onIncomingMessage *func(hub *WebSocketHub, clientGuid string, clientAttributes *ClientAttributes, r *http.Request, msg ClientMessage, ctx context.Context)
}
type funcHandlerOption struct {
f func(*handlerOptions)
}
func (fdo *funcHandlerOption) apply(do *handlerOptions) {
fdo.f(do)
}
func newFuncHandlerOption(f func(*handlerOptions)) *funcHandlerOption {
return &funcHandlerOption{f: f}
}
func WithUhttpHandler(h uhttp.Handler) HandlerOption {
return newFuncHandlerOption(func(o *handlerOptions) {
o.uhttpHandler = h
})
}
func WithClientAttributes(f func(hub *WebSocketHub, r *http.Request) (*ClientAttributes, error)) HandlerOption {
return newFuncHandlerOption(func(o *handlerOptions) {
o.clientAttributes = &f
})
}
func WithWelcomeMessages(f func(hub *WebSocketHub, clientGuid string, clientAttributes *ClientAttributes, r *http.Request, ctx context.Context) ([][]byte, error)) HandlerOption {
return newFuncHandlerOption(func(o *handlerOptions) {
o.welcomeMessages = &f
})
}
func WithOnConnect(f func(hub *WebSocketHub, clientGuid string, clientAttributes *ClientAttributes, r *http.Request, ctx context.Context)) HandlerOption {
return newFuncHandlerOption(func(o *handlerOptions) {
o.onConnect = &f
})
}
func WithOnError(f func(hub *WebSocketHub, clientGuid string, clientAttributes *ClientAttributes, r *http.Request, err error, ctx context.Context)) HandlerOption {
return newFuncHandlerOption(func(o *handlerOptions) {
o.onError = &f
})
}
func WithOnIncomingMessage(f func(hub *WebSocketHub, clientGuid string, clientAttributes *ClientAttributes, r *http.Request, msg ClientMessage, ctx context.Context)) HandlerOption {
return newFuncHandlerOption(func(o *handlerOptions) {
o.onIncomingMessage = &f
})
}