aboutsummaryrefslogtreecommitdiff
path: root/config.go
diff options
context:
space:
mode:
Diffstat (limited to 'config.go')
-rw-r--r--config.go77
1 files changed, 77 insertions, 0 deletions
diff --git a/config.go b/config.go
new file mode 100644
index 0000000..002f317
--- /dev/null
+++ b/config.go
@@ -0,0 +1,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")
+ }
+}