• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang go-flags.Parse函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/jessevdk/go-flags.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Parse函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
	}
}
开发者ID:RUNDSP,项目名称:ggeohash,代码行数:60,代码来源:ggeohash_cli.go


示例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.")
	}
}
开发者ID:nulpunt,项目名称:nulpunt,代码行数:36,代码来源:flags.go


示例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
}
开发者ID:NHOrus,项目名称:ponydownloader,代码行数:28,代码来源:settings.go


示例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)
}
开发者ID:smithjm,项目名称:peekaboo,代码行数:59,代码来源:main.go


示例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)
	}
}
开发者ID:cention-mujibur-rahman,项目名称:go-in-practice,代码行数:9,代码来源:go_flags_example.go


示例6: readOptions

func readOptions() *options {
	o := options{}

	_, err := flags.Parse(&o)
	if err != nil {
		panic(err)
	}

	return &o
}
开发者ID:dsoprea,项目名称:go-pathfingerprint,代码行数:10,代码来源:main.go


示例7: readOptions

func readOptions() *options {
	o := options{}

	_, err := flags.Parse(&o)
	if err != nil {
		os.Exit(1)
	}

	return &o
}
开发者ID:dsoprea,项目名称:go-gpxreader,代码行数:10,代码来源:main.go


示例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())
}
开发者ID:bluestatedigital,项目名称:centralbooking,代码行数:55,代码来源:main.go


示例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
}
开发者ID:jordansissel,项目名称:fingerpoken,代码行数:14,代码来源:cli.go


示例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]
}
开发者ID:changwng,项目名称:sqliteweb,代码行数:15,代码来源:main.go


示例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)
}
开发者ID:mfya,项目名称:autobld,代码行数:16,代码来源:config.go


示例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)
}
开发者ID:DarkSwoop,项目名称:platform-skvs,代码行数:16,代码来源:server.go


示例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))
	}
}
开发者ID:mickep76,项目名称:go-sampleapp,代码行数:46,代码来源:go-sampleapp.go


示例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 {}
}
开发者ID:bluestatedigital,项目名称:postpone,代码行数:43,代码来源:main.go


示例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
}
开发者ID:politician,项目名称:goose,代码行数:20,代码来源:main.go


示例16: 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.ProxyAddr == "" {
		opts.ProxyAddr = opts.ListenAddr
	}

	switch {
	case opts.Rate < 1:
		opts.Rate = 2
	case opts.Rate > 10:
		opts.Rate = 10
	}

	return opts
}
开发者ID:politician,项目名称:go-proxymate,代码行数:22,代码来源:main.go


示例17: main

func main() {
	var opts Options

	_, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}

	docker, err := dockerapi.NewClient(getopt("DOCKER_HOST", "unix:///var/run/docker.sock"))
	assert(err)

	hosts := NewHosts(docker, opts.File.Filename, opts.DomainName)

	// set up to handle events early, so we don't miss anything while doing the
	// initial population
	events := make(chan *dockerapi.APIEvents)
	assert(docker.AddEventListener(events))

	containers, err := docker.ListContainers(dockerapi.ListContainersOptions{})
	assert(err)

	for _, listing := range containers {
		go hosts.Add(listing.ID)
	}

	log.Println("docker-hosts: Listening for Docker events...")
	for msg := range events {
		switch msg.Status {
		case "start":
			go hosts.Add(msg.ID)

		case "die":
			go hosts.Remove(msg.ID)
		}
	}

	log.Fatal("docker-hosts: docker event loop closed") // todo: reconnect?
}
开发者ID:iverasp,项目名称:docker-hosts,代码行数:38,代码来源:main.go


示例18: 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)

	deviceMux := http.NewServeMux()
	deviceMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		p := r.URL.Path
		r.URL.Path = "/devices" + p
		handler(w, r)
	})
	go http.ListenAndServe(":82", deviceMux)

	http.HandleFunc("/", handler)
	http.ListenAndServe(":"+strconv.Itoa(opts.Port), nil)
}
开发者ID:experimental-platform,项目名称:platform-skvs,代码行数:24,代码来源:server.go


示例19: main

func main() {
	var settings Settings
	_, 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)
		}
	}

	broker_endpoint := "inproc://fancy-req"
	server_cert, err := czmq.NewCertFromFile(settings.ServerCertificatePath)
	if err != nil {
		log.Error(err.Error())
		os.Exit(1)
	}

	agent, _ := zap.NewZapAgent()
	// TODO(sissel): Gate access to prevent untrusted connections.
	go agent.Run(zap.NewRestrictedAccess())
	defer agent.Destroy()

	b, err := mdp.NewBroker(broker_endpoint)
	if err != nil {
		log.Fatalf("NewBroker(%s) failed: %s", broker_endpoint, err)
	}
	b.CurveCertificate = server_cert
	b.Bind("inproc://fancy-dealer")
	port, err := b.Bind("tcp://*:*")
	log.WithFields(log.Fields{"address": fmt.Sprintf("tcp://*:%d", port)}).Info("Broker available")
	go RunHTTP(":8111", "/zws/1.0")
	b.Run()
}
开发者ID:jordansissel,项目名称:fingerpoken,代码行数:36,代码来源:main.go


示例20: main

func main() {
	println("Starting monlite...")
	// Configuration
	var opts options
	_, err := flags.Parse(&opts)
	if err != nil {
		log.Fatal("can't parse the command line options:", err)
	}
	cfg, err := ini.Load(opts.Conf)
	if err != nil {
		log.Fatal("Error reading configuratio file:", opts.Conf)
	}

	// Log stuff
	println("Log...")
	name := appname
	pid := os.Getpid()
	pidstr := strconv.FormatInt(int64(pid), 10)
	name = name + " (" + pidstr + ")"

	fnull, err := os.OpenFile("/dev/null", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
	if err != nil {
		log.Fatal("open log file failed:", err)
	}
	defer fnull.Close()
	stderrBack := log.NewWriter(fnull).F(log.DefFormatter)
	if opts.Level != "" && opts.Level != "nolog" {
		level, err := log.ParseLevel(opts.Level)
		if err != nil {
			log.Fatal("Invalid log level.")
		}
		stderrBack = log.Filter(
			log.NewWriter(os.Stderr).F(log.DefFormatter),
			log.Op(log.Ge, "level", level),
		)
	}

	logfile := cfg.Section("log").Key("file").MustString("/var/log/monlite.log")
	if opts.Log != "" {
		logfile = opts.Log
	}
	loglevel := cfg.Section("log").Key("level").MustString("debug")
	level, err := log.ParseLevel(loglevel)
	if err != nil {
		log.Fatal("Invalid log level.")
	}
	var fileBack log.LogBackend
	if logfile != "" {
		f, err := os.OpenFile(logfile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
		if err != nil {
			log.Fatalf("open log file %v failed: %v", logfile, err)
		}
		defer f.Close()
		fileBack = log.Filter(
			log.NewWriter(f).F(log.DefFormatter),
			log.Op(log.Ge, "level", level),
		)
	}

	log.Log = log.New(stderrBack, true).Domain(name).InfoLevel()
	if fileBack != nil {
		log.Log = log.New(
			log.NewMulti(
				stderrBack,
				log.DefFormatter,
				fileBack,
				log.DefFormatter,
			),
			true,
		).Domain(name).InfoLevel()
	}

	log.Println("Log Ok!")

	dns.SetLookupHostFunction(net.LookupHost)

	log.Println("Configuration...")

	cfgMail := cfg.Section("mail")

	smtpTimeout, err := cfgMail.Key("timeout").Int()
	if err != nil {
		log.Fatal("invalid smtp timeout")
	}

	server := cfgMail.Key("smtp").String()
	s := strings.Split(server, ":")
	if len(s) > 0 {
		server = s[0]
	}

	auth := smtp.PlainAuth(
		"",
		cfgMail.Key("account").String(),
		cfgMail.Key("password").String(),
		server,
	)

	hostname := "your system"
	if hn, err := os.Hostname(); err == nil {
//.........这里部分代码省略.........
开发者ID:fcavani,项目名称:monlite,代码行数:101,代码来源:main.go



注:本文中的github.com/jessevdk/go-flags.Parse函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang go-flags.ParseArgs函数代码示例发布时间:2022-05-23
下一篇:
Golang go-flags.NewParser函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap