-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.go
More file actions
66 lines (57 loc) · 1.64 KB
/
Copy pathloader.go
File metadata and controls
66 lines (57 loc) · 1.64 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
package config
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
// LoadConfigFile loads configuration from a file into cfg.
// The format is auto-detected from the file extension:
// - .json → JSON
// - .yaml/.yml → YAML
func LoadConfigFile(path string, cfg interface{}) error {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("open config file: %w", err)
}
defer func() { _ = file.Close() }()
switch strings.ToLower(filepath.Ext(path)) {
case ".json":
if err := json.NewDecoder(file).Decode(cfg); err != nil {
return fmt.Errorf("decode JSON config: %w", err)
}
case ".yaml", ".yml":
if err := yaml.NewDecoder(file).Decode(cfg); err != nil {
return fmt.Errorf("decode YAML config: %w", err)
}
default:
return fmt.Errorf("unsupported config file format: %s", filepath.Ext(path))
}
return nil
}
// LoadJSON loads configuration specifically from a JSON file into cfg.
func LoadJSON(path string, cfg interface{}) error {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("open JSON config file: %w", err)
}
defer func() { _ = file.Close() }()
if err := json.NewDecoder(file).Decode(cfg); err != nil {
return fmt.Errorf("decode JSON config: %w", err)
}
return nil
}
// LoadYAML loads configuration specifically from a YAML file into cfg.
func LoadYAML(path string, cfg interface{}) error {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("open YAML config file: %w", err)
}
defer func() { _ = file.Close() }()
if err := yaml.NewDecoder(file).Decode(cfg); err != nil {
return fmt.Errorf("decode YAML config: %w", err)
}
return nil
}