package main import ( "flag" "github.com/caarlos0/env" "os" "path" ) func DefaultConfig() Config { c := Config{ RootPath: "./", APIkey: "thisIsNotASecretTokenNow", Host: "localhost", Port: "6889", Title: "Shrty", } c.DB = c.RootPath + "shrty.db" 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 } // Setting Rootpath from flag or enviorment and set the db path to new root. f.StringVar(&config.RootPath, "root", config.RootPath, "The path to the shrty root directory.") f.StringVar(&config.DB, "db-file", config.DB, "The db file to use") if config.DB == "./shrty.db" && config.RootPath != "./" { config.DB = path.Join(config.RootPath, "shrty.db") } // Setting up all the other flags 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.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 }