-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
68 lines (54 loc) · 1.2 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
package main
import (
"fmt"
"os"
"regexp"
)
type Config struct {
Port string
Dir string
}
func (config *Config) validate() error {
// Port
validPort := regexp.MustCompile(`^[0-9]+$`)
if !validPort.MatchString(config.Port) {
return fmt.Errorf("configured port \"%s\" is not valid", config.Port)
}
// Dir
if stat, err := os.Stat(config.Dir); err != nil || !stat.IsDir() {
return fmt.Errorf("configured dir \"%s\" is not valid", config.Dir)
}
return nil
}
func NewConfig() (*Config, error) {
config := new(Config)
// take config from multiple sources
//
// priority, from least to most:
//
// - config file (not implemented)
// - environment variable
// - command line switch (not implemented)
envConfig := NewConfigFromEnv()
config.apply(envConfig)
// always validate config
if err := config.validate(); err != nil {
return config, err
}
return config, nil
}
func (config *Config) apply(add *Config) {
if add.Port != "" {
config.Port = add.Port
}
if add.Dir != "" {
config.Dir = add.Dir
}
}
// create Config from environment variables
func NewConfigFromEnv() *Config {
config := new(Config)
config.Port = os.Getenv("PORT")
config.Dir = os.Getenv("DIR")
return config
}