go-paste/cmd/paste/config.go
2018-03-16 08:10:34 -06:00

119 lines
2.5 KiB
Go

package main
import (
"bytes"
"fmt"
"github.com/docopt/docopt.go"
"github.com/spf13/viper"
"sour.is/x/toolbox/httpsrv"
"sour.is/x/toolbox/log"
_ "sour.is/x/toolbox/stats"
)
var (
// AppVersion Application Version Number
AppVersion string
// AppBuild Application Build Number
AppBuild string
)
// AppName name of the application
var AppName = "Paste API"
// AppUsage displays runtime options
var AppUsage = `Paste API
Usage:
paste version
paste [ -v | -vv ] serve
Options:
-v Log info to console.
-vv Log debug to console.
-l <ListenAddress>, --listen=<ListenAddress> Address to listen on.
-c <ConfigDir>, --config=<ConfigDir> Set Config Directory.
Config:
The config file is read from the following locations:
- <ConfigDir>
- /etc/opt/sour.is/paste/
- Working Directory
`
var defaultConfig = `
[http]
listen = ":9010"
[module.paste]
random = "4096"
store = "data/"
`
var args map[string]interface{}
func init() {
var err error
if args, err = docopt.Parse(AppUsage, nil, true, AppVersion, false); err != nil {
log.Fatal(err)
}
if args["-v"].(int) == 1 {
log.SetVerbose(log.Vinfo)
}
if args["-v"].(int) == 2 {
log.SetVerbose(log.Vdebug)
log.Debug("Debug Logging.")
}
viper.SetConfigName("config")
if args["--config"] != nil {
viper.AddConfigPath(args["--config"].(string))
}
viper.AddConfigPath("/etc/opt/sour.is/paste/")
viper.AddConfigPath(".")
viper.SetConfigType("toml")
viper.ReadConfig(bytes.NewBuffer([]byte(defaultConfig)))
err = viper.MergeInConfig()
if err != nil { // Handle errors reading the config file
log.Fatalf("Fatal error config file: %s \n", err)
}
viper.Set("app.name", AppName)
viper.SetDefault("app.version", "VERSION")
if AppVersion != "" {
viper.Set("app.version", AppVersion)
}
viper.SetDefault("app.build", "SNAPSHOT")
if AppBuild != "" {
viper.Set("app.build", AppBuild)
}
if args["serve"] == true {
if args["--listen"] != nil {
viper.Set("http.listen", args["--listen"].(string))
}
log.Noticef("Startup: %s (%s %s)",
viper.GetString("app.name"),
viper.GetString("app.version"),
viper.GetString("app.build"))
log.Notice("Read config from: ", viper.ConfigFileUsed())
httpsrv.Config()
} else if args["version"] == true {
fmt.Printf("Version: %s (%s %s)\n",
viper.GetString("app.name"),
viper.GetString("app.version"),
viper.GetString("app.build"))
}
}