2021-07-23 16:06:19 +00:00
|
|
|
package storage
|
|
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
2021-07-23 16:06:19 +00:00
|
|
|
|
2021-08-27 19:10:03 +00:00
|
|
|
"github.com/qdm12/gluetun/internal/models"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
var _ Flusher = (*Storage)(nil)
|
|
|
|
|
|
|
|
|
|
type Flusher interface {
|
2022-05-27 00:59:47 +00:00
|
|
|
FlushToFile(allServers *models.AllServers) error
|
2021-08-27 19:10:03 +00:00
|
|
|
}
|
|
|
|
|
|
2022-05-27 00:59:47 +00:00
|
|
|
func (s *Storage) FlushToFile(allServers *models.AllServers) error {
|
2021-07-23 16:06:19 +00:00
|
|
|
return flushToFile(s.filepath, allServers)
|
|
|
|
|
}
|
2021-08-27 19:10:03 +00:00
|
|
|
|
2022-05-27 00:59:47 +00:00
|
|
|
func flushToFile(path string, servers *models.AllServers) 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
|
|
|
|
|
}
|
|
|
|
|
encoder := json.NewEncoder(file)
|
|
|
|
|
encoder.SetIndent("", " ")
|
|
|
|
|
if err := encoder.Encode(servers); err != nil {
|
|
|
|
|
_ = file.Close()
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
return file.Close()
|
|
|
|
|
}
|