2021-07-23 16:06:19 +00:00
|
|
|
package storage
|
|
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
|
|
|
|
)
|
|
|
|
|
|
2022-06-05 14:58:46 +00:00
|
|
|
// FlushToFile flushes the merged servers data to the file
|
|
|
|
|
// specified by path, as indented JSON.
|
|
|
|
|
func (s *Storage) FlushToFile(path string) error {
|
|
|
|
|
s.mergedMutex.RLock()
|
|
|
|
|
defer s.mergedMutex.RUnlock()
|
2021-08-27 19:10:03 +00:00
|
|
|
|
2022-06-05 14:58:46 +00:00
|
|
|
return s.flushToFile(path)
|
2021-07-23 16:06:19 +00:00
|
|
|
}
|
2021-08-27 19:10:03 +00:00
|
|
|
|
2022-06-05 14:58:46 +00:00
|
|
|
// flushToFile flushes the merged servers data to the file
|
|
|
|
|
// specified by path, as indented JSON. It is not thread-safe.
|
|
|
|
|
func (s *Storage) flushToFile(path string) error {
|
2021-08-27 19:10:03 +00:00
|
|
|
dirPath := filepath.Dir(path)
|
|
|
|
|
if err := os.MkdirAll(dirPath, 0644); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2022-06-05 14:58:46 +00:00
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
encoder := json.NewEncoder(file)
|
|
|
|
|
encoder.SetIndent("", " ")
|
2022-06-05 14:58:46 +00:00
|
|
|
|
|
|
|
|
err = encoder.Encode(&s.mergedServers)
|
|
|
|
|
if err != nil {
|
2021-08-27 19:10:03 +00:00
|
|
|
_ = file.Close()
|
|
|
|
|
return err
|
|
|
|
|
}
|
2022-06-05 14:58:46 +00:00
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
return file.Close()
|
|
|
|
|
}
|