/
goconfig.go
50 lines (41 loc) · 968 Bytes
/
goconfig.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
package config
import (
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"time"
"gopkg.in/yaml.v2"
)
type Config interface{}
func ConfigFromFile(path string, cfg Config) error {
f, err := os.OpenFile(path, os.O_RDONLY | os.O_SYNC, 0)
if err != nil {
return err
}
defer f.Close()
switch ext := strings.ToLower(filepath.Ext(path)); ext {
case ".yaml", ".yml":
err = ParseYAML(f, cfg)
case ".json":
err = ParseJSON(f, cfg)
}
return err
}
func ParseYAML(r io.Reader, cfg Config) error {
return yaml.NewDecoder(r).Decode(cfg)
}
func ParseJSON(r io.Reader, cfg Config) error {
return json.NewDecoder(r).Decode(cfg)
}
type ServerConfig struct {
Host string `yaml:host`
Port string `yaml:port`
ReadTimeout time.Duration `yaml:readtimeout`
WriteTimeout time.Duration `yaml:writetimeout`
}
func ServerConfigFromYaml(filepath string) (cfg ServerConfig, err error) {
err = ConfigFromFile(filepath, &cfg)
return cfg, err
}