Add a lock to the states file
This commit is contained in:
parent
1e12b7b37c
commit
acf425b705
|
@ -4,12 +4,19 @@ import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"os"
|
"os"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
var statesFile = "data/states.json"
|
var (
|
||||||
|
statesLock sync.Mutex
|
||||||
|
statesFile = "data/states.json"
|
||||||
|
)
|
||||||
|
|
||||||
// DoesStatesFileExist .
|
// DoesStatesFileExist .
|
||||||
func DoesStatesFileExist() (bool, error) {
|
func DoesStatesFileExist() (bool, error) {
|
||||||
|
statesLock.Lock()
|
||||||
|
defer statesLock.Unlock()
|
||||||
|
|
||||||
if _, err := os.Stat(statesFile); err != nil {
|
if _, err := os.Stat(statesFile); err != nil {
|
||||||
if !os.IsNotExist(err) {
|
if !os.IsNotExist(err) {
|
||||||
return false, errors.WithStack(err)
|
return false, errors.WithStack(err)
|
||||||
|
@ -29,6 +36,10 @@ func FetchServerStates() (map[string]string, error) {
|
||||||
return nil, errors.WithStack(err)
|
return nil, errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Request a lock after we check if the file exists.
|
||||||
|
statesLock.Lock()
|
||||||
|
defer statesLock.Unlock()
|
||||||
|
|
||||||
// Return an empty map if the file does not exist.
|
// Return an empty map if the file does not exist.
|
||||||
if !exists {
|
if !exists {
|
||||||
return map[string]string{}, nil
|
return map[string]string{}, nil
|
||||||
|
@ -70,6 +81,10 @@ func SaveServerStates() error {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Request a lock after we check if the file exists.
|
||||||
|
statesLock.Lock()
|
||||||
|
defer statesLock.Unlock()
|
||||||
|
|
||||||
// Create the file if it doesn't exist or open it if it already does.
|
// Create the file if it doesn't exist or open it if it already does.
|
||||||
var f *os.File
|
var f *os.File
|
||||||
if !exists {
|
if !exists {
|
||||||
|
|
Loading…
Reference in New Issue
Block a user