Create a gist now

Instantly share code, notes, and snippets.

@jgoulah /config.go Secret
Last active Aug 29, 2015

package config
import (
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"sync"
"github.etsycorp.com/Engineering/myapp/Godeps/_workspace/src/code.google.com/p/gcfg"
)
var Config = &configuration{}
func (cfg *configuration) Load() error {
fdir := filepath.Dir(pathToThisFile())
cdir := getConfigDir()
config := []string{fmt.Sprintf("%s/../config.cfg", fdir), fmt.Sprintf("%s/config.cfg", cdir)}
paths := make([]string, 0)
paths = findConfig(config, paths)
secrets_config := []string{fmt.Sprintf("%s/../config-secrets.cfg", fdir), "/etc/myapp/config-secrets.cfg"}
paths = findConfig(secrets_config, paths)
cfg.mtx.Lock()
defer cfg.mtx.Unlock()
for _, p := range paths {
log.Printf("reading config: %s\n", p)
err := gcfg.ReadFileInto(cfg, p)
if err != nil {
return err
}
}
return nil
}
// the issue with runtime.Caller(0) is it assumes the binary is run from
// the same location as it was built
func pathToThisFile() string {
_, file, _, _ := runtime.Caller(0)
return file
}
// because of the above issue, we also use os.Getwd() to look for the config file
func getConfigDir() string {
wdir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
// hack for when working dir is subdir
config_location := "."
if filepath.Base(wdir) != "myapp" {
config_location = ".."
}
return fmt.Sprintf("%s/%s", wdir, config_location)
}
func findConfig(locations []string, paths []string) []string {
for _, c := range locations {
if _, err := os.Stat(c); err == nil {
paths = append(paths, c)
return paths
}
}
return paths
}
type configuration struct {
mtx sync.Mutex
Server struct {
Port int
}
Mail struct {
Key string
EmailAddress string `gcfg:"email-address"`
SMTP_Host string `gcfg:"smtp-host"`
Port int
}
Database map[string]*struct {
User string
Password string
Hostname string
Port int
Name string
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment