This repository has been archived by the owner on Sep 19, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.go
74 lines (62 loc) · 1.57 KB
/
server.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
// Copyright 2017 The go-oceanconnect authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package oceanconnect
import (
"encoding/json"
"io/ioutil"
"net/http"
"sync"
"github.com/sirupsen/logrus"
)
type NotificationFunc func(interface{}) error
type Server struct {
cbsLock sync.RWMutex
cbs map[Notification]NotificationFunc
}
func (s *Server) handler(w http.ResponseWriter, r *http.Request) {
buf, err := ioutil.ReadAll(r.Body)
if err != nil {
return
}
var n struct {
NotifyType string `json:"notifyType"`
}
if err := json.Unmarshal(buf, &n); err != nil {
logrus.Errorf("error decoding notification type")
return
}
if err := s.runCallback(Notification(n.NotifyType), buf); err != nil {
logrus.Errorf("Error running callback: %v", err)
return
}
}
func (s *Server) runCallback(not Notification, dec []byte) error {
s.cbsLock.RLock()
defer s.cbsLock.RUnlock()
if s.cbs == nil {
logrus.Infof("no callbacks registered, callback received")
}
cb, ok := s.cbs[not]
if ok {
v, err := notificationDeserializer(not, dec)
if err != nil {
return err
}
return cb(v)
}
logrus.Debugf("no callback registered for %s", string(not))
return nil
}
func (s *Server) ListenAndServe(uri string) error {
http.HandleFunc("/", s.handler)
return http.ListenAndServe(uri, nil)
}
func (s *Server) RegisterCallback(not Notification, cb NotificationFunc) {
s.cbsLock.Lock()
if s.cbs == nil {
s.cbs = make(map[Notification]NotificationFunc)
}
s.cbs[not] = cb
s.cbsLock.Unlock()
}