Declarative command line argument parser for golang projects.
Install go module
go get github.com/memclutter/confparse
Use struct
tags to declare command-line arguments.
// ...
type Config struct {
Argument1 string `name:"arg1" usage:"Argument 1 help text"`
Timeout time.Duration `name:"timeout" value:"200ms" usage:"Timeout argument"`
}
// ...
Different types of arguments are supported:
string
by default any arguments is a stringint
like1
,2
,300
,-23
etctime.Duration
for time interval argument, like10s
,500ms
,20us
etcbool
for boolean argument
Use special struct tag envVar
if you application read configuration from environment variables.
Set environment variable name in envVar
and confparse read value from there.
The following is an example of defining a configuration for a simple web server
package main
import (
"log"
"net/http"
"github.com/memclutter/confparse"
)
type Config struct {
Addr string `name:"addr" value:":8000" usage:"Listen and serve address"`
ApiKey string `name:"apiKey" envVar:"API_KEY" usage:"API key"`
}
var appConfig = &Config{}
func main() {
if err := confparse.Parse(appConfig); err != nil {
log.Fatalf("Error parse configuration: %s", err)
}
log.Printf("API Key: %s", appConfig.ApiKey)
log.Printf("Listen and serve on %s", appConfig.Addr)
if err := http.ListenAndServe(appConfig.Addr, nil); err != nil {
log.Fatalf("Listen and serve error: %s", err)
}
}