本文整理汇总了Golang中github.com/jessevdk/go-flags.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Parse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
// Parse flags from `args'. Note that here we use flags.ParseArgs for
// the sake of making a working example. Normally, you would simply use
// flags.Parse(&opts) which uses os.Args
args, err := flags.Parse(&opts)
if err != nil {
os.Exit(0)
return
}
if opts.Verbose {
fmt.Printf("Verbosity: %v\n", opts.Verbose)
fmt.Printf("Encode: %v\n", opts.Encode)
fmt.Printf("Decode: %v\n", opts.Decode)
fmt.Printf("Neighbor: %v\n", opts.Neighbor)
fmt.Printf("Latitude: %v\n", opts.Latitude)
fmt.Printf("Longitude: %v\n", opts.Longitude)
fmt.Printf("Precision: %v\n", opts.Precision)
fmt.Printf("GeoHash: '%v'\n", opts.GeoHash)
fmt.Printf("Remaining args: [%s]\n", strings.Join(args, " "))
}
// Shorthand to make the code below readable
location := ggeohash.MakePreciseLocationLowerBound()
location.Latitude = opts.Latitude
location.Longitude = opts.Longitude
precision := (opts.Precision)
geo := opts.GeoHash
if opts.Encode {
output := ggeohash.Encode(location, precision)
fmt.Printf("latitude = %2.10f, longitude = %3.10f, precision = %d, geohash = %s\n", location.Latitude, location.Longitude, precision, output)
}
if opts.Decode {
output := ggeohash.Decode(geo)
fmt.Printf("geohash = %s, latitude = %2.10f, longitude = %3.10f, latitude.err = %2.10f, longitude.err = %3.10f\n", geo, output.Location.Latitude, output.Location.Longitude, output.Error.Latitude, output.Error.Longitude)
}
if opts.Neighbor {
directions := [2]ggeohash.CardialDirections{ggeohash.None, ggeohash.None}
if opts.North {
directions[0] = ggeohash.North
}
if opts.South {
directions[0] = ggeohash.South
}
if opts.East {
directions[1] = ggeohash.East
}
if opts.West {
directions[1] = ggeohash.West
}
output := ggeohash.Neighbor(geo, directions)
fmt.Printf("geohash = %s, directions[0] = %d, directions[1] = %d, neighbor = %s\n", geo, directions[0], directions[1], string(output))
}
}
示例2: initFlags
// initFlags parses the given flags.
// when the user asks for help (-h or --help): the application exists with status 0
// when unexpected flags is given: the application exits with status 1
func initFlags() {
args, err := goflags.Parse(&flags)
if err != nil {
// assert the err to be a flags.Error
flagError := err.(*goflags.Error)
if flagError.Type == goflags.ErrHelp {
// user asked for help on flags.
// program can exit successfully
os.Exit(0)
}
if flagError.Type == goflags.ErrUnknownFlag {
fmt.Println("Use --help to view all available options.")
os.Exit(1)
}
fmt.Printf("Error parsing flags: %s\n", err)
os.Exit(1)
}
// check for unexpected arguments
// when an unexpected argument is given: the application exists with status 1
if len(args) > 0 {
fmt.Printf("Unknown argument '%s'.\n", args[0])
os.Exit(1)
}
if flags.DisableAlphaAuth {
log.Printf("DEPRECATED flag --disable-alpha-auth: alpha auth has been stripped from the source code, therefore --disable-alpha-auth is of no use anymore. It will be removed in future release.")
}
if flags.HTTPFiles != "./http-files/" {
log.Printf("DEPRECATED flag --http-files: loading of the http files is now done with go.rice. This flag be removed in future release.")
}
}
示例3: Setup
//Setup reads static config from file and runtime options from commandline
//It also preserves static config for later comparsion with runtime to prevent
//rewriting it when no changes are made
func (opts *Options) Setup() ([]string, *Config) {
err := flag.IniParse("config.ini", opts)
if err != nil {
switch err.(type) {
default:
lFatal(err)
case *os.PathError:
lWarn("config.ini not found, using defaults")
}
}
inisets := *opts.Config //copy value instead of reference - or we will get no results later
args, err := flag.Parse(opts)
checkFlagError(err) //Here we scream if something goes wrong and provide help if something goes meh.
for _, arg := range os.Args {
if strings.Contains(arg, "--score") {
opts.ScoreF = true
}
if strings.Contains(arg, "--faves") {
opts.FavesF = true
}
}
return args, &inisets
}
示例4: main
func main() {
// Set log options.
log.SetOutput(os.Stderr)
log.SetLevel(log.WarnLevel)
// Options.
var opts struct {
Verbose bool `short:"v" long:"verbose" description:"Verbose"`
Version bool `long:"version" description:"Version"`
BindAddr string `short:"b" long:"bind-addr" description:"Bind to address" default:"0.0.0.0"`
Port int `short:"p" long:"port" description:"Port" default:"5050"`
StaticDir string `short:"s" long:"static-dir" description:"Static content" default:"static"`
TemplateDir string `short:"t" long:"template-dir" description:"Templates" default:"templates"`
}
// Parse options.
if _, err := flags.Parse(&opts); err != nil {
ferr := err.(*flags.Error)
if ferr.Type == flags.ErrHelp {
os.Exit(0)
} else {
log.Fatal(err.Error())
}
}
// Print version.
if opts.Version {
fmt.Printf("peekaboo %s\n", Version)
os.Exit(0)
}
// Set verbose.
if opts.Verbose {
log.SetLevel(log.InfoLevel)
}
// Check root.
if runtime.GOOS != "darwin" && os.Getuid() != 0 {
log.Fatal("This application requires root privileges to run.")
}
info, err := hwinfo.Get()
if err != nil {
log.Fatal(err.Error())
}
log.Infof("Using static dir: %s", opts.StaticDir)
log.Infof("Using template dir: %s", opts.TemplateDir)
m := macaron.Classic()
m.Use(macaron.Static(opts.StaticDir))
m.Use(macaron.Renderer(macaron.RenderOptions{
Directory: opts.TemplateDir,
IndentJSON: true,
}))
routes(m, info)
m.Run(opts.BindAddr, opts.Port)
}
示例5: main
func main() {
flags.Parse(&opts)
if opts.Spanish == true {
fmt.Printf("Hola %s!\n", opts.Name)
} else {
fmt.Printf("Hello %s!\n", opts.Name)
}
}
示例6: readOptions
func readOptions() *options {
o := options{}
_, err := flags.Parse(&o)
if err != nil {
panic(err)
}
return &o
}
示例7: readOptions
func readOptions() *options {
o := options{}
_, err := flags.Parse(&o)
if err != nil {
os.Exit(1)
}
return &o
}
示例8: main
func main() {
var opts Options
_, err := flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
if opts.Debug {
log.SetLevel(log.DebugLevel)
}
if opts.LogFile != "" {
logFp, err := os.OpenFile(opts.LogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
checkError(fmt.Sprintf("error opening %s", opts.LogFile), err)
defer logFp.Close()
// ensure panic output goes to log file
syscall.Dup2(int(logFp.Fd()), 1)
syscall.Dup2(int(logFp.Fd()), 2)
// log as JSON
log.SetFormatter(&log.JSONFormatter{})
// send output to file
log.SetOutput(logFp)
}
log.Debug("hi there! (tickertape tickertape)")
log.Infof("version: %s", version)
vaultClient, err := helpers.NewVaultClient(opts.VaultAddr, opts.VaultToken)
checkError("creating Vault client", err)
consulClient, err := consulapi.NewClient(consulapi.DefaultConfig())
checkError("creating Consul client", err)
router := mux.NewRouter()
registrar := instance.NewRegistrar(vaultClient)
v1 := v1.NewCentralBooking(
registrar,
consulClient.Catalog(),
vaultClient.GetEndpoint(),
)
v1.InstallHandlers(router.PathPrefix("/v1").Subrouter())
httpServer := &http.Server{
Addr: fmt.Sprintf(":%d", opts.HttpPort),
Handler: Log(router),
}
checkError("launching HTTP server", httpServer.ListenAndServe())
}
示例9: ParseArgs
func ParseArgs(settings interface{}) []string {
remaining, err := flags.Parse(settings)
if err != nil {
switch err.(*flags.Error).Type {
case flags.ErrHelp:
os.Exit(0)
default:
log.Error(err.Error())
os.Exit(1)
}
}
return remaining
}
示例10: initOptions
// initOptions initialize the command line options.
func initOptions() {
_, err := flags.Parse(&options)
utils.ExitOnError(err, "error parsing options")
// TODO: Add support for env variables
if options.Version {
printHeader()
os.Exit(0)
}
// Remove all flags to make sure that Goji doesn't read them
os.Args = os.Args[:1]
}
示例11: Parse
// Parse returns a configuration from either a configuration file or flags.
func Parse() (*Config, error) {
opts := &opts{}
if _, err := goflags.Parse(opts); err != nil {
return nil, err
}
if opts.Quiet {
log.SetLevel(-1)
} else {
log.SetLevel(len(opts.Verbose))
}
if opts.ConfigPath == "" {
return parseArgs(opts)
}
return parseFile(opts.ConfigPath)
}
示例12: main
func main() {
flags.Parse(&opts)
opts.DataPath, _ = filepath.Abs(opts.DataPath)
fmt.Println("DATA_PATH:", opts.DataPath)
fmt.Println("PORT:", opts.Port)
for i, hookUrl := range opts.WebHookUrls {
if len(hookUrl) >= 4 && hookUrl[:4] != "http" {
opts.WebHookUrls[i] = "http://" + hookUrl
}
}
fmt.Printf("HOOKS: %+v\n", opts.WebHookUrls)
http.HandleFunc("/", handler)
http.ListenAndServe(":"+strconv.Itoa(opts.Port), nil)
}
示例13: main
func main() {
// Set log options.
log.SetOutput(os.Stderr)
log.SetLevel(log.WarnLevel)
// Options.
var opts struct {
Verbose bool `short:"v" long:"verbose" description:"Verbose"`
Version bool `long:"version" description:"Version"`
File *string `short:"f" long:"file" description:"Input file, data serialization format used is based on the file extension"`
}
// Parse options.
if _, err := flags.Parse(&opts); err != nil {
ferr := err.(*flags.Error)
if ferr.Type == flags.ErrHelp {
os.Exit(0)
} else {
log.Fatal(err.Error())
}
}
// Print version.
if opts.Version {
fmt.Printf("tf %s\n", Version)
os.Exit(0)
}
// Set verbose.
if opts.Verbose {
log.SetLevel(log.InfoLevel)
}
// Get file is specified.
if opts.File != nil {
// Load file.
d, err := input.LoadFile(*opts.File)
if err != nil {
log.Fatal(err.Error())
}
// Print as YAML.
s, err := yaml.Marshal(&d)
fmt.Println(string(s))
}
}
示例14: main
func main() {
var opts Opts
_, err := flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
if logFp := common.InitLogging(opts.Debug, opts.LogFile); logFp != nil {
defer logFp.Close()
}
log.Debug("hi there! (tickertape tickertape)")
log.Infof("version: %s", version)
cfgBytes, err := ioutil.ReadFile(opts.Config)
common.CheckError("reading config file", err)
var schedule []Schedule
common.CheckError("parsing config file", yaml.Unmarshal(cfgBytes, &schedule))
log.Errorf("%+v", schedule)
common.ConfigureWorkers(opts.RedisHost, opts.RedisPort, opts.RedisDb)
c := cron.New()
for _, e := range schedule {
// some weird scoping going on here
func(entry Schedule) {
c.AddFunc(entry.Spec, func() {
jid, err := workers.Enqueue(entry.Queue, entry.Class, entry.Args)
common.CheckError("scheduling something", err)
log.WithField("something", entry.Spec).Infof("submitted job %s", jid)
})
}(e)
}
c.Start()
select {}
}
示例15: parseArgs
// Parses the command-line arguments, and validates them.
func parseArgs() *Options {
opts := &Options{}
_, err := goflags.Parse(opts)
if err != nil {
os.Exit(1)
}
if opts.RedisDb < 0 || opts.RedisDb > 15 {
log.Fatal("redis db out of range")
}
opts.verbosity = 0
if opts.Verbose {
opts.verbosity += 1
}
return opts
}