-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
91 lines (82 loc) · 2.03 KB
/
config.go
File metadata and controls
91 lines (82 loc) · 2.03 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Package config helps to load a configuration file into the structure.
// This library supports yaml, json formats of files or slice of bytes.
package config
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"path/filepath"
"reflect"
"gopkg.in/yaml.v3"
)
var (
ErrDataNull = errors.New("bytes must not be a null")
ErrDataEmpty = errors.New("bytes must not be an empty slice")
ErrNotImplemented = errors.New("file's format is not implemented")
ErrNotPointer = errors.New("param must be a pointer to a struct or a map")
ErrReadFile = errors.New("read config file")
ErrDecodeData = errors.New("decode config")
)
// FromFile unmarshals data from a file into a structure.
func FromFile(cfg interface{}, pathToFile string) error {
if !isPointer(cfg) {
return ErrNotPointer
}
fileData, err := ioutil.ReadFile(pathToFile)
if err != nil {
return fmt.Errorf("%w: %s", ErrReadFile, err)
}
ext := filepath.Ext(pathToFile)
fileType := detectType(ext)
switch fileType {
case TypeYaml:
err = fromYaml(fileData, cfg)
case TypeJson:
err = fromJson(fileData, cfg)
default:
return ErrNotImplemented
}
if err != nil {
return fmt.Errorf("%w (%s): %s", ErrDecodeData, fileType, err)
}
return nil
}
// FromBytes unmarshals data from a slice of data into a structure.
func FromBytes(cfg interface{}, data []byte, t typeFile) error {
if !isPointer(cfg) {
return ErrNotPointer
}
if data == nil {
return ErrDataNull
}
if len(data) == 0 {
return ErrDataEmpty
}
var err error
switch t {
case TypeYaml:
err = fromYaml(data, cfg)
case TypeJson:
err = fromJson(data, cfg)
default:
return ErrNotImplemented
}
if err != nil {
return fmt.Errorf("%w (%s): %s", ErrDecodeData, t, err)
}
return nil
}
func fromJson(data []byte, cfg interface{}) error {
return json.Unmarshal(data, cfg)
}
func fromYaml(data []byte, cfg interface{}) error {
return yaml.Unmarshal(data, cfg)
}
func isPointer(cfg interface{}) bool {
if cfg == nil {
return false
}
t := reflect.TypeOf(cfg)
return t.Kind() == reflect.Ptr
}