blob: 002f317b51a1737a06e50deeec959e4424b31e82 (
plain) (
blame)
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
|
package main
import (
"fmt"
"os"
"reflect"
)
type Config struct {
HttpListen string `env:"BAGAGE_HTTP_LISTEN" default:":8080"`
DavPath string `env:"BAGAGE_WEBDAV_PREFIX" default:"/webdav"`
LdapServer string `env:"BAGAGE_LDAP_ENDPOINT" default:"127.0.0.1:1389"`
UserBaseDN string `env:"BAGAGE_LDAP_USER_BASE_DN" default:"ou=users,dc=deuxfleurs,dc=fr"`
UserNameAttr string `env:"BAGAGE_LDAP_USERNAME_ATTR" default:"cn"`
Endpoint string `env:"BAGAGE_S3_ENDPOINT" default:"garage.deuxfleurs.fr"`
UseSSL bool `env:"BAGAGE_S3_SSL" default:"true"`
}
func (c *Config) LoadWithDefault() *Config {
c.iter(func(t reflect.StructField, v reflect.Value) {
tag := t.Tag.Get("default")
if tag == "" {
return
} else {
setKey(v, tag)
}
})
return c
}
func (c *Config) LoadWithEnv() *Config {
c.iter(func(t reflect.StructField, v reflect.Value) {
tag := t.Tag.Get("env")
if tag == "" {
return
} else if val, ok := os.LookupEnv(tag); ok {
setKey(v, val)
}
})
return c
}
func (c *Config) String() (rep string) {
rep = "Configuration:\n"
c.iter(func(t reflect.StructField, v reflect.Value) {
rep += "\t" + t.Name + ": "
if t.Type.Kind() == reflect.Bool {
rep += fmt.Sprintf("%v", v.Bool()) + "\n"
} else {
rep += "\"" + v.String() + "\"\n"
}
})
return
}
func (c *Config) iter(cb func(t reflect.StructField, v reflect.Value)) {
t := reflect.ValueOf(c).Elem()
for i := 0; i < t.Type().NumField(); i++ {
field := t.Field(i)
typeField := t.Type().Field(i)
cb(typeField, field)
}
}
func setKey(v reflect.Value, e string) {
if v.Type().Kind() == reflect.String {
v.SetString(e)
} else if v.Type().Kind() == reflect.Bool {
v.SetBool(e == "true")
} else {
panic("Unsupported type")
}
}
|