Files
cv-site/internal/fileutil/json.go
T

36 lines
766 B
Go
Raw Normal View History

package fileutil
import (
"encoding/json"
"fmt"
"os"
)
// LoadJSON loads and unmarshals JSON from a file into the target struct.
// It automatically searches for the file using FindDataFile and handles
// all error wrapping with context.
//
// Example:
//
// var cv CV
// if err := fileutil.LoadJSON("data/cv-en.json", &cv); err != nil {
// log.Fatal(err)
// }
func LoadJSON(filename string, target interface{}) error {
filepath, err := FindDataFile(filename)
if err != nil {
return err
}
data, err := os.ReadFile(filepath)
if err != nil {
return fmt.Errorf("error reading file %s: %w", filename, err)
}
if err := json.Unmarshal(data, target); err != nil {
return fmt.Errorf("error parsing JSON from %s: %w", filename, err)
}
return nil
}