-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader_json.go
42 lines (36 loc) · 1.07 KB
/
loader_json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Copyright The ActForGood Authors.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://github.com/actforgood/xconf/blob/main/LICENSE.
package xconf
import (
"encoding/json"
"io"
"os"
)
// JSONFileLoader loads JSON configuration from a file.
// The location of JSON content based file is given as parameter.
func JSONFileLoader(filePath string) Loader {
return LoaderFunc(func() (map[string]any, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer f.Close()
return JSONReaderLoader(f).Load()
})
}
// JSONReaderLoader loads JSON configuration from an [io.Reader].
func JSONReaderLoader(reader io.Reader) Loader {
return LoaderFunc(func() (map[string]any, error) {
if seekReader, ok := reader.(io.Seeker); ok {
_, _ = seekReader.Seek(0, io.SeekStart) // move to the beginning in case of a re-load needed.
}
var configMap map[string]any
dec := json.NewDecoder(reader)
if err := dec.Decode(&configMap); err != nil {
return nil, err
}
return configMap, nil
})
}