aboutsummaryrefslogblamecommitdiff
path: root/config.go
blob: c5aff5b935c23f8d7076c6a35bc1f716ec8e93ab (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16















                                                                                                   
                                                                        
                                                                   




























































                                                                        
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"`
	S3Cache      string `env:"BAGAGE_S3_CACHE" default:"./s3_cache"`
	SSHKey       string `env:"BAGAGE_SSH_KEY" default:"id_rsa"`
}

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")
	}
}