package main import ( "flag" "github.com/caarlos0/env" "os" ) func DefaultConfig() Config { c := Config{ RootPath: "./", APIkey: "thisIsNotASecretTokenNow", Host: "localhost", Port: "6889", Title: "Sgot", } c.DB = c.RootPath + "shrty.go" return c } type Config struct { RootPath string `env:"SHRTY_ROOT_PATH"` DB string `env:"SHRTY_DB_FILE"` APIkey string `env:"SHRTY_API_KEY"` Host string `env:"SHRTY_HOST"` Port string `env:"SHRTY_PORT"` Domain string `env:"SHRTY_DOMAIN"` Title string `env:"SHRTY_TITLE"` CheckDomain bool `env:"SHRTY_CHECK_DOMAIN"` } func (c Config) HostPort() string { return c.Host + ":" + c.Port } func ReadConfig() *Config { c, err := readConfig(flag.NewFlagSet(os.Args[0], flag.ExitOnError), os.Args[1:]) if err != nil { // sould never happen, because of flag default policy ExitOnError panic(err) } return c } func readConfig(f *flag.FlagSet, args []string) (*Config, error){ config := DefaultConfig() // Environment variables err := env.Parse(&config) if err != nil { return nil, err } f.StringVar(&config.RootPath, "root", config.RootPath, "The path to the shrty root directory.") f.StringVar(&config.Host, "host", config.Host, "The host to listen on") f.StringVar(&config.Port, "port", config.Port, "The port to listen on") f.StringVar(&config.APIkey, "apikey", config.APIkey, "The Key to connect to the API") f.StringVar(&config.DB, "db-file", config.DB, "The db file to use") f.StringVar(&config.Domain, "domain", config.Domain, "The domain for redirect links") f.StringVar(&config.Title, "title", config.Title, "The title on the Front") // Arguments variables err = f.Parse(args) if err != nil { return nil, err } return &config, err }