-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmux.go
73 lines (57 loc) · 1.55 KB
/
mux.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
package plasma
import (
"github.com/specspace/plasma/protocol"
"sync"
)
type ServeMux struct {
handlers map[protocol.State]map[byte]Handler
mu sync.RWMutex
}
func NewServeMux() *ServeMux {
return &ServeMux{
handlers: map[protocol.State]map[byte]Handler{
protocol.StateHandshaking: {},
protocol.StateStatus: {},
protocol.StateLogin: {},
protocol.StatePlay: {},
},
mu: sync.RWMutex{},
}
}
func (mux *ServeMux) Handle(state protocol.State, packetID byte, handler Handler) {
mux.mu.Lock()
defer mux.mu.Unlock()
if handler == nil {
panic("plasma: nil handler")
}
mux.handlers[state][packetID] = handler
}
func (mux *ServeMux) HandleFunc(state protocol.State, packetID byte, handler func(w ResponseWriter, r *Request)) {
if handler == nil {
panic("plasma: nil handler")
}
mux.Handle(state, packetID, HandlerFunc(handler))
}
func (mux *ServeMux) Handler(r *Request) (Handler, byte) {
mux.mu.RLock()
defer mux.mu.RUnlock()
handler, ok := mux.handlers[r.conn.state][r.Packet.ID]
if !ok {
return nil, r.Packet.ID
}
return handler, r.Packet.ID
}
func (mux *ServeMux) ServeProtocol(w ResponseWriter, r *Request) {
handler, _ := mux.Handler(r)
if handler == nil {
return
}
handler.ServeProtocol(w, r)
}
var DefaultServeMux = NewServeMux()
func Handle(state protocol.State, packetID byte, handler Handler) {
DefaultServeMux.Handle(state, packetID, handler)
}
func HandleFunc(state protocol.State, packetID byte, handler func(w ResponseWriter, r *Request)) {
DefaultServeMux.HandleFunc(state, packetID, handler)
}