Clarify comunication interface

This commit is contained in:
Knut Ahlers 2020-11-23 09:54:02 +01:00
parent c902fbe230
commit 0c41f447f7
Signed by: luzifer
GPG key ID: 0066F03ED215AD7D

28
api.go
View file

@ -16,20 +16,24 @@ import (
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
) )
const ( const msgTypeStore string = "store"
msgTypeStore string = "store"
)
var subscriptions = newSubscriptionStore() var subscriptions = newSubscriptionStore()
type socketMessage struct {
Payload interface{} `json:"payload"`
Type string `json:"type"`
Version string `json:"version"`
}
type subcriptionStore struct { type subcriptionStore struct {
socketSubscriptions map[string]func(interface{}) error socketSubscriptions map[string]func(socketMessage) error
socketSubscriptionsLock *sync.RWMutex socketSubscriptionsLock *sync.RWMutex
} }
func newSubscriptionStore() *subcriptionStore { func newSubscriptionStore() *subcriptionStore {
return &subcriptionStore{ return &subcriptionStore{
socketSubscriptions: map[string]func(msg interface{}) error{}, socketSubscriptions: map[string]func(socketMessage) error{},
socketSubscriptionsLock: new(sync.RWMutex), socketSubscriptionsLock: new(sync.RWMutex),
} }
} }
@ -47,7 +51,7 @@ func (s subcriptionStore) SendAllSockets(msgType string, msg interface{}) error
return nil return nil
} }
func (s *subcriptionStore) SubscribeSocket(id string, hdl func(interface{}) error) { func (s *subcriptionStore) SubscribeSocket(id string, hdl func(socketMessage) error) {
s.socketSubscriptionsLock.Lock() s.socketSubscriptionsLock.Lock()
defer s.socketSubscriptionsLock.Unlock() defer s.socketSubscriptionsLock.Unlock()
@ -61,7 +65,7 @@ func (s *subcriptionStore) UnsubscribeSocket(id string) {
delete(s.socketSubscriptions, id) delete(s.socketSubscriptions, id)
} }
func compileSocketMessage(msgType string, msg interface{}) map[string]interface{} { func compileSocketMessage(msgType string, msg interface{}) socketMessage {
assetVersionsLock.RLock() assetVersionsLock.RLock()
defer assetVersionsLock.RUnlock() defer assetVersionsLock.RUnlock()
@ -75,10 +79,10 @@ func compileSocketMessage(msgType string, msg interface{}) map[string]interface{
ver := fmt.Sprintf("%x", hash.Sum(nil)) ver := fmt.Sprintf("%x", hash.Sum(nil))
return map[string]interface{}{ return socketMessage{
"payload": msg, Payload: msg,
"type": msgType, Type: msgType,
"version": ver, Version: ver,
} }
} }
@ -106,7 +110,7 @@ func handleUpdateSocket(w http.ResponseWriter, r *http.Request) {
connLock = new(sync.Mutex) connLock = new(sync.Mutex)
id = uuid.Must(uuid.NewV4()).String() id = uuid.Must(uuid.NewV4()).String()
) )
subscriptions.SubscribeSocket(id, func(msg interface{}) error { subscriptions.SubscribeSocket(id, func(msg socketMessage) error {
connLock.Lock() connLock.Lock()
defer connLock.Unlock() defer connLock.Unlock()