forked from gernest/utron
/
config.go
168 lines (153 loc) · 4.06 KB
/
config.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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package utron
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"github.com/BurntSushi/toml"
"github.com/fatih/camelcase"
"gopkg.in/yaml.v2"
)
// Config stores configurations values
type Config struct {
AppName string `json:"app_name" yaml:"app_name" toml:"app_name"`
BaseURL string `json:"base_url" yaml:"base_url" toml:"base_url"`
Port int `json:"port" yaml:"port" toml:"port"`
Verbose bool `json:"verbose" yaml:"verbose" toml:"verbose"`
StaticDir string `json:"static_dir" yaml:"static_dir" toml:"static_dir"`
ViewsDir string `json:"view_dir" yaml:"view_dir" toml:"view_dir"`
Database string `json:"database" yaml:"database" toml:"database"`
DatabaseConn string `json:"database_conn" yaml:"database_conn" toml:"database_conn"`
}
// DefaultConfig returns the default configuation settings.
func DefaultConfig() *Config {
return &Config{
AppName: "utron web app",
BaseURL: "http://localhost:8090",
Port: 8090,
Verbose: false,
StaticDir: "static",
ViewsDir: "views",
}
}
// NewConfig reads configuration from path. The format is deductted from file extension
// * .json - is decoded as json
// * .yml - is decoded as yaml
// * .toml - is decoded as toml
func NewConfig(path string) (*Config, error) {
_, err := os.Stat(path)
if err != nil {
return nil, err
}
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
cfg := &Config{}
switch filepath.Ext(path) {
case ".json":
jerr := json.Unmarshal(data, cfg)
if jerr != nil {
return nil, jerr
}
case ".toml":
_, terr := toml.Decode(string(data), cfg)
if terr != nil {
return nil, terr
}
case ".yml":
yerr := yaml.Unmarshal(data, cfg)
if yerr != nil {
return nil, yerr
}
default:
return nil, errors.New("utron: config file not supported")
}
return cfg, nil
}
// saveToFile saves the Config in the file named path. This is a helper method
// for generating sample configuration files.
func (c *Config) saveToFile(path string) error {
var data []byte
switch filepath.Ext(path) {
case ".json":
d, err := json.MarshalIndent(c, "", "\t") // use tab indent to make it human friendly
if err != nil {
return err
}
data = d
case ".yml":
d, err := yaml.Marshal(c)
if err != nil {
return err
}
data = d
case ".toml":
b := &bytes.Buffer{}
err := toml.NewEncoder(b).Encode(c)
if err != nil {
return err
}
data = b.Bytes()
}
return ioutil.WriteFile(path, data, 0600)
}
// SyncEnv overides c field's values that are set in the environment.
//
// The environment variable names are derived from config fields by underscoring, and upper
// cassing the name. e.g AppName will have a corresponding environment variable APP_NAME
//
// NOTE only int, string and bool fields are supported and the corresponding values are set.
// when the field value is not supported it is ignored.
func (c *Config) SyncEnv() error {
cfg := reflect.ValueOf(c).Elem()
cTyp := cfg.Type()
for k := range make([]struct{}, cTyp.NumField()) {
field := cTyp.Field(k)
cm := getEnvName(field.Name)
env := os.Getenv(cm)
if env == "" {
continue
}
switch field.Type.Kind() {
case reflect.String:
cfg.FieldByName(field.Name).SetString(env)
case reflect.Int:
v, err := strconv.Atoi(env)
if err != nil {
return fmt.Errorf("utron: loading config field %s %v", field.Name, err)
}
cfg.FieldByName(field.Name).Set(reflect.ValueOf(v))
case reflect.Bool:
b, err := strconv.ParseBool(env)
if err != nil {
return fmt.Errorf("utron: loading config field %s %v", field.Name, err)
}
cfg.FieldByName(field.Name).SetBool(b)
}
}
return nil
}
// getEnvName returns all upper case and underscore separated string, from field.
// field is a camel case string.
//
// example
// AppName wrill chage to APP_NAME
func getEnvName(field string) string {
camSplit := camelcase.Split(field)
var rst string
for k, v := range camSplit {
if k == 0 {
rst = strings.ToUpper(v)
continue
}
rst = rst + "_" + strings.ToUpper(v)
}
return rst
}