Adjust settings functions
This commit is contained in:
parent
c295d20b1a
commit
06eaff6503
2 changed files with 22 additions and 32 deletions
48
cfg/cfg.go
48
cfg/cfg.go
|
@ -2,58 +2,44 @@ package cfg
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/alecthomas/kong"
|
||||
)
|
||||
|
||||
type AppSettings struct {
|
||||
ServerAddress string
|
||||
DataFile string
|
||||
DataURL string
|
||||
}
|
||||
|
||||
var cliStruct struct {
|
||||
ServerAddress string `name:"listen-address" env:"GEOIP_LISTEN_ADDRESS" help:"Address to use for the metrics server" default:"${default_address}"`
|
||||
DataFile string `name:"data-file" env:"GEOIP_DATA_FILE" help:"path to data file" default:"${default_file_path}"`
|
||||
DataURL string `name:"data-url" env:"GEOIP_DATA_URL" help:"url to data file" default:"${default_file_url}"`
|
||||
DataURL string `name:"data-url" env:"GEOIP_DATA_URL" help:"url to data file"`
|
||||
}
|
||||
|
||||
func Parse() *AppSettings {
|
||||
func NewAppSettings() *AppSettings {
|
||||
return &AppSettings{}
|
||||
}
|
||||
|
||||
func (s *AppSettings) Parse() error {
|
||||
ctx := kong.Parse(
|
||||
&cliStruct,
|
||||
s,
|
||||
kong.Vars{
|
||||
"default_address": ":8080",
|
||||
"default_file_path": "./data.csv",
|
||||
"default_file_url": "https://data.example.com/test.csv",
|
||||
},
|
||||
kong.Name("country_geo_locations"),
|
||||
kong.Description("🚀 Start a simple web server for GeoIP data"),
|
||||
kong.UsageOnError(),
|
||||
)
|
||||
|
||||
validateFlags(ctx)
|
||||
settings := &AppSettings{
|
||||
ServerAddress: cliStruct.ServerAddress,
|
||||
DataFile: cliStruct.DataFile,
|
||||
DataURL: cliStruct.DataURL,
|
||||
err := validateFlags(*s)
|
||||
if err != nil {
|
||||
ctx.PrintUsage(false)
|
||||
fmt.Println()
|
||||
return err
|
||||
}
|
||||
return settings
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateFlags(cliCtx *kong.Context) {
|
||||
var flagsValid = true
|
||||
var messages = []string{}
|
||||
if cliStruct.ServerAddress == "" {
|
||||
messages = append(messages, "error: invalid server address, must not be blank")
|
||||
flagsValid = false
|
||||
}
|
||||
if !flagsValid {
|
||||
cliCtx.PrintUsage(false)
|
||||
fmt.Println()
|
||||
for i := 0; i < len(messages); i++ {
|
||||
fmt.Println(messages[i])
|
||||
}
|
||||
os.Exit(1)
|
||||
func validateFlags(settings AppSettings) error {
|
||||
if settings.DataURL == "" {
|
||||
return fmt.Errorf("error: invalid data url, must not be blank")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
6
main.go
6
main.go
|
@ -18,7 +18,11 @@ import (
|
|||
)
|
||||
|
||||
func main() {
|
||||
appSettings := cfg.Parse()
|
||||
appSettings := cfg.NewAppSettings()
|
||||
if err := appSettings.Parse(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
handleGracefulShutdown()
|
||||
if !downloader.FileExists(appSettings.DataFile) {
|
||||
downloader.DownloadFile(appSettings.DataFile, appSettings.DataURL)
|
||||
|
|
Loading…
Reference in a new issue