5
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2024-11-25 01:51:35 +00:00

Override config from environment. See #50

Expects uppercase environment variables of MATTERBRIDGE_PROTOCOL_ACCOUNT_KEY="value"
e.g. you can override this config

[mattermost]
    [mattermost.work]
    Team="yourteam"
    Login="yourlogin"
    Password="yourpass"

by using
MATTERBRIDGE_MATTERMOST_WORK_TEAM="newteam"
MATTERBRIDGE_MATTERMOST_WORK_LOGIN="newlogin"
MATTERBRIDGE_MATTERMOST_WORK_PASSWORD="newpassword"
This commit is contained in:
Wim 2016-10-30 22:32:29 +01:00
parent 96620a3c2c
commit 92d9db5a2d
2 changed files with 42 additions and 0 deletions

View File

@ -25,6 +25,8 @@ func New(cfg *config.Config, bridge *config.Bridge, c chan config.Message) Bridg
accInfo := strings.Split(bridge.Account, ".") accInfo := strings.Split(bridge.Account, ".")
protocol := accInfo[0] protocol := accInfo[0]
name := accInfo[1] name := accInfo[1]
// override config from environment
config.OverrideCfgFromEnv(cfg, protocol, name)
switch protocol { switch protocol {
case "mattermost": case "mattermost":
return bmattermost.New(cfg.Mattermost[name], name, c) return bmattermost.New(cfg.Mattermost[name], name, c)

View File

@ -3,6 +3,9 @@ package config
import ( import (
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"log" "log"
"os"
"reflect"
"strings"
) )
type Message struct { type Message struct {
@ -80,3 +83,40 @@ func NewConfig(cfgfile string) *Config {
} }
return &cfg return &cfg
} }
func OverrideCfgFromEnv(cfg *Config, protocol string, account string) {
var protoCfg Protocol
val := reflect.ValueOf(cfg).Elem()
// loop over the Config struct
for i := 0; i < val.NumField(); i++ {
typeField := val.Type().Field(i)
// look for the protocol map (both lowercase)
if strings.ToLower(typeField.Name) == protocol {
// get the Protocol struct from the map
data := val.Field(i).MapIndex(reflect.ValueOf(account))
protoCfg = data.Interface().(Protocol)
protoStruct := reflect.ValueOf(&protoCfg).Elem()
// loop over the found protocol struct
for i := 0; i < protoStruct.NumField(); i++ {
typeField := protoStruct.Type().Field(i)
// build our environment key (eg MATTERBRIDGE_MATTERMOST_WORK_LOGIN)
key := "matterbridge_" + protocol + "_" + account + "_" + typeField.Name
key = strings.ToUpper(key)
// search the environment
res := os.Getenv(key)
// if it exists and the current field is a string
// then update the current field
if res != "" {
fieldVal := protoStruct.Field(i)
if fieldVal.Kind() == reflect.String {
log.Printf("config: overriding %s from env with %s\n", key, res)
fieldVal.Set(reflect.ValueOf(res))
}
}
}
// update the map with the modified Protocol (cfg.Protocol[account] = Protocol)
val.Field(i).SetMapIndex(reflect.ValueOf(account), reflect.ValueOf(protoCfg))
break
}
}
}