forked from plgd-dev/go-coap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenhandler.go
56 lines (50 loc) · 1.35 KB
/
tokenhandler.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
package coap
import "sync"
func handleBySessionTokenHandler(w ResponseWriter, r *Request, next HandlerFunc) {
r.Client.networkSession.TokenHandler().Handle(w, r, next)
}
//TokenHandler container for regirstration handlers by token
type TokenHandler struct {
tokenHandlers map[[MaxTokenSize]byte]HandlerFunc
tokenHandlersLock sync.Mutex
}
//Handle call handler for request if exist otherwise use next
func (s *TokenHandler) Handle(w ResponseWriter, r *Request, next HandlerFunc) {
//validate token
var token [MaxTokenSize]byte
copy(token[:], r.Msg.Token())
s.tokenHandlersLock.Lock()
h := s.tokenHandlers[token]
s.tokenHandlersLock.Unlock()
if h != nil {
h(w, r)
return
}
if next != nil {
next(w, r)
}
}
//Add register handler for token
func (s *TokenHandler) Add(token []byte, handler func(w ResponseWriter, r *Request)) error {
var t [MaxTokenSize]byte
copy(t[:], token)
s.tokenHandlersLock.Lock()
defer s.tokenHandlersLock.Unlock()
if s.tokenHandlers[t] != nil {
return ErrTokenAlreadyExist
}
s.tokenHandlers[t] = handler
return nil
}
//Remove unregister handler for token
func (s *TokenHandler) Remove(token []byte) error {
var t [MaxTokenSize]byte
copy(t[:], token)
s.tokenHandlersLock.Lock()
defer s.tokenHandlersLock.Unlock()
if s.tokenHandlers[t] == nil {
return ErrTokenNotExist
}
delete(s.tokenHandlers, t)
return nil
}