Load loads an existing JSONFileData from the given path. If the file does not exist, Load returns an error that can be checked with os.IsNotExist. Load and New are separate to avoid creating a new file when starting a service, which could lead to data loss. To both load an existing file or create
(path string)
| 48 | // db, err = jsonfile.New[Data](path) |
| 49 | // } |
| 50 | func Load[Data any](path string) (*JSONFile[Data], error) { |
| 51 | p := &JSONFile[Data]{path: path, data: new(Data)} |
| 52 | var err error |
| 53 | p.bytes, err = os.ReadFile(path) |
| 54 | if err != nil { |
| 55 | return nil, fmt.Errorf("jsonfile.Load: %w", err) |
| 56 | } |
| 57 | if err := json.Unmarshal(p.bytes, p.data); err != nil { |
| 58 | return nil, fmt.Errorf("jsonfile.Load: %w", err) |
| 59 | } |
| 60 | return p, nil |
| 61 | } |
| 62 | |
| 63 | // Read calls fn with the current copy of the data. |
| 64 | func (p *JSONFile[Data]) Read(fn func(data *Data)) { |
nothing calls this directly
no outgoing calls
no test coverage detected
searching dependent graphs…