Add mutexes around saving the files

This commit is contained in:
Peter Stuifzand 2018-12-10 19:33:32 +01:00
parent bd733bac71
commit 35d8d0d8d8

View File

@ -13,6 +13,7 @@ import (
"os"
"strconv"
"strings"
"sync"
"time"
)
@ -43,8 +44,11 @@ type Stat struct {
}
type subscriptionHandler struct {
LockSubs sync.Mutex
Subscribers map[string][]Subscriber
Stats map[string]Stat
LockStats sync.Mutex
Stats map[string]Stat
}
func (handler *subscriptionHandler) handlePublish(w http.ResponseWriter, r *http.Request) error {
@ -147,6 +151,7 @@ func (handler *subscriptionHandler) handleUnsubscription(w http.ResponseWriter,
func (handler *subscriptionHandler) handleSubscription(w http.ResponseWriter, r *http.Request) error {
log.Printf("subscription request received: %s %#v\n", r.URL.String(), r.Form)
callback := r.Form.Get("hub.callback")
topic := r.Form.Get("hub.topic")
secret := r.Form.Get("hub.secret")
@ -319,6 +324,9 @@ func (handler *subscriptionHandler) loadStats() error {
}
func (handler *subscriptionHandler) loadSubscriptions() error {
handler.LockStats.Lock()
defer handler.LockStats.Unlock()
file, err := os.Open("./subscription.json")
if err != nil {
if os.IsExist(err) {
@ -343,6 +351,8 @@ func (handler *subscriptionHandler) load() error {
}
func (handler *subscriptionHandler) saveStats() error {
handler.LockStats.Lock()
defer handler.LockStats.Unlock()
file, err := os.Create("./stats.json")
if err != nil {
return err
@ -355,6 +365,9 @@ func (handler *subscriptionHandler) saveStats() error {
}
func (handler *subscriptionHandler) saveSubscriptions() error {
handler.LockSubs.Lock()
defer handler.LockSubs.Unlock()
file, err := os.Create("./subscription.json")
if err != nil {
return err