Convenient way to load/save JSON data
This commit is contained in:
parent
bee853cc6a
commit
cc5107d0db
40
tools/utils/cached_values.go
Normal file
40
tools/utils/cached_values.go
Normal file
@ -0,0 +1,40 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type CachedValues[T any] struct {
|
||||
Name string
|
||||
Opts T
|
||||
}
|
||||
|
||||
func (self *CachedValues[T]) Path() string {
|
||||
return filepath.Join(CacheDir(), self.Name+".json")
|
||||
}
|
||||
|
||||
func (self *CachedValues[T]) Load() T {
|
||||
raw, err := os.ReadFile(self.Path())
|
||||
if err == nil {
|
||||
json.Unmarshal(raw, self.Opts)
|
||||
}
|
||||
return self.Opts
|
||||
}
|
||||
|
||||
func (self *CachedValues[T]) Save() {
|
||||
raw, err := json.Marshal(self.Opts)
|
||||
if err == nil {
|
||||
os.WriteFile(self.Path(), raw, 0600)
|
||||
}
|
||||
}
|
||||
|
||||
func NewCachedValues[T any](name string, initial_val T) *CachedValues[T] {
|
||||
return &CachedValues[T]{Name: name, Opts: initial_val}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user