-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloader.go
54 lines (45 loc) · 1.22 KB
/
loader.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
43
44
45
46
47
48
49
50
51
52
53
54
package morph
import (
"encoding/json"
"fmt"
"os"
"strings"
"gopkg.in/yaml.v2"
)
// Loaders is the collection of loaders by file extension.
var Loaders = map[string]Loader{
"yaml": YAMLLoader{},
"yml": YAMLLoader{},
"json": JSONLoader{},
}
// Load loads the configuration from the provided file.
func Load(path string) (Configuration, error) {
extension := path[strings.LastIndex(path, ".")+1:]
loader, ok := Loaders[extension]
if !ok {
return Configuration{}, fmt.Errorf("morph: no loader for files with %q extension", extension)
}
return loader.Load(path)
}
// Loader loads the cofiguration from the provided file.
type Loader interface {
Load(path string) (Configuration, error)
}
type JSONLoader struct{}
// Load loads the configuration from the JSON file provided.
func (l JSONLoader) Load(path string) (c Configuration, err error) {
var file []byte
if file, err = os.ReadFile(path); err != nil {
return
}
return c, json.Unmarshal(file, &c)
}
type YAMLLoader struct{}
// Load loads the configuration from the YAML file provided.
func (l YAMLLoader) Load(path string) (c Configuration, err error) {
var file []byte
if file, err = os.ReadFile(path); err != nil {
return
}
return c, yaml.Unmarshal(file, &c)
}