56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
package update
|
|
|
|
import (
|
|
domain "RenewCMS/internal/domain/update"
|
|
"encoding/json"
|
|
"os"
|
|
"path/filepath"
|
|
"sync"
|
|
)
|
|
|
|
const statusFilePermissions = 0o600
|
|
|
|
type JSONStatusStore struct {
|
|
path string
|
|
mu sync.Mutex
|
|
}
|
|
|
|
var _ domain.StatusStore = &JSONStatusStore{}
|
|
|
|
func NewJSONStatusStore(path string) *JSONStatusStore {
|
|
return &JSONStatusStore{path: path}
|
|
}
|
|
|
|
func (s *JSONStatusStore) Load() (domain.CheckResult, bool) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
content, err := os.ReadFile(s.path)
|
|
if err != nil {
|
|
return domain.CheckResult{}, false
|
|
}
|
|
var result domain.CheckResult
|
|
if err := json.Unmarshal(content, &result); err != nil || result.CheckedAt.IsZero() {
|
|
return domain.CheckResult{}, false
|
|
}
|
|
return result, true
|
|
}
|
|
|
|
func (s *JSONStatusStore) Save(result domain.CheckResult) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
content, err := json.Marshal(result)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(s.path), os.ModePerm); err != nil {
|
|
return err
|
|
}
|
|
temporary := s.path + ".tmp"
|
|
if err := os.WriteFile(temporary, content, statusFilePermissions); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(temporary, s.path)
|
|
}
|