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

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

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

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



在下文中一共展示了ParseArgs函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: main

func main() {

	junk, err := flags.ParseArgs(&opts, os.Args)

	if len(junk) != 1 {
		fmt.Printf("Usage: Invalid arguments supplied, %s\n", junk)
		os.Exit(1)
	}
	if err != nil {
		os.Exit(1)
	}

	port = fmt.Sprintf("%d", opts.Port)
	if opts.HostIP != "localhost" {
		host_ip = opts.HostIP
	}

	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	server.On("connection", func(so socketio.Socket) {
		log.Println("on connection")
		so.Join("chat")
		so.On("chat message", func(msg string) {
			m := make(map[string]interface{})
			m["a"] = "你好" // hello there
			e := so.Emit("cn1111", m)
			//这个没有问题			// this is no problem
			fmt.Println("\n\n")

			b := make(map[string]string)
			b["u-a"] = "中文内容" //这个不能是中文		// this is chineese // this can not be chineese
			m["b-c"] = b
			e = so.Emit("cn2222", m)
			log.Println(e)

			log.Println("emit:", so.Emit("chat message", msg))
			so.BroadcastTo("chat", "chat message", msg)
		})
		so.On("t45", func(msg string) {
			err := so.Emit("r45", "Yep")
			if err != nil {
				fmt.Printf("Error: %s\n", err)
			}
		})
		so.On("disconnection", func() {
			log.Println("on disconnect")
		})
	})
	server.On("error", func(so socketio.Socket, err error) {
		log.Println("error:", err)
	})

	http.Handle("/socket.io/", server)
	http.Handle("/", http.FileServer(http.Dir("./asset")))
	fmt.Printf("Serving on port %s, brows to http://localhost:%s/\n", port, port)
	listen := fmt.Sprintf("%s:%s", host_ip, port)
	log.Fatal(http.ListenAndServe(listen, nil))
}
开发者ID:pschlump,项目名称:socketio,代码行数:60,代码来源:main.go


示例2: TestCoreLoopRetryDidRetry

func TestCoreLoopRetryDidRetry(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	statefile, err := ioutil.TempFile("./testdata", "")
	if err != nil {
		t.Fatal(err)
	}

	defer func() {
		os.Remove(statefile.Name())
		statefile.Close()
	}()

	arguments := "--retries=3 -- ./testdata/works-after-two-failures.sh " + statefile.Name()
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	var logstream bytes.Buffer

	log.SetOutput(&output)

	err = CoreLoopRetry(args, &logstream)
	t.Log(output.String())
	t.Log(logstream.String())
	if err != nil {
		t.Error("want no error, got", err)
	}
}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:32,代码来源:core_test.go


示例3: main

func main() {

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

	if opts.ClearTopic {
		clearTopic(opts.Topic)
	}

	if opts.KeyPrefix != "" {
		KEY_PREFIX = opts.KeyPrefix + "-"
	}

	if opts.ProcessorHost != "" {
		if !strings.HasSuffix(opts.ProcessorHost, "/") {
			PROCESSOR_HOST = opts.ProcessorHost
		} else {
			fmt.Println("Cannot have a hostname that ends with a slash, try again.")
			os.Exit(1)
		}
	}

	if opts.ProcessorPort != "" {
		PROCESSOR_PORT = opts.ProcessorPort
	}

	err = filepath.Walk(string(opts.Path), visit)
	if err != nil {
		fmt.Printf("Error saving log files: %s\n", err)
	}
}
开发者ID:kwilsonO,项目名称:log-daemon,代码行数:33,代码来源:log-daemon.go


示例4: init

func init() {
	_, err := flags.ParseArgs(&options, os.Args)

	if err != nil {
		os.Exit(1)
	}
}
开发者ID:hi-trust,项目名称:friendfeed,代码行数:7,代码来源:main.go


示例5: main

func main() {
	var opts struct {
		DBPath   string `short:"f" long:"file" description:"Path to GeoIP database" value-name:"FILE" default:""`
		Listen   string `short:"l" long:"listen" description:"Listening address" value-name:"ADDR" default:":8080"`
		CORS     bool   `short:"x" long:"cors" description:"Allow requests from other domains" default:"false"`
		Template string `short:"t" long:"template" description:"Path to template" default:"index.html"`
	}
	_, err := flags.ParseArgs(&opts, os.Args)
	if err != nil {
		os.Exit(1)
	}

	var a *api.API
	if opts.DBPath == "" {
		a = api.New()
	} else {
		a, err = api.NewWithGeoIP(opts.DBPath)
		if err != nil {
			log.Fatal(err)
		}
	}

	a.CORS = opts.CORS
	a.Template = opts.Template

	log.Printf("Listening on %s", opts.Listen)
	if err := a.ListenAndServe(opts.Listen); err != nil {
		log.Fatal(err)
	}
}
开发者ID:breezhang,项目名称:ifconfigd,代码行数:30,代码来源:main.go


示例6: getDefaultOptions

func getDefaultOptions() *options {
	opts := &options{}
	if _, err := gflags.ParseArgs(opts, nil); err != nil {
		panic(err)
	}
	opts.PProfOptions.BinaryFile = testPProfInputFile
	return opts
}
开发者ID:ZhuoRoger,项目名称:go-torch,代码行数:8,代码来源:main_test.go


示例7: TestPuppetDetailedExitCodes

func TestPuppetDetailedExitCodes(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--monitor-ok=2 --monitor-warning=4 --monitor-warning=6 --monitor-critical=1 -- true"
	_, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	err = validateOptionConstraints()
	if err != nil {
		t.Errorf("want no error, got %s", err)
	}
}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:11,代码来源:flags_test.go


示例8: TestDefaulSettingsOk

func TestDefaulSettingsOk(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "-- true"
	_, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	err = validateOptionConstraints()
	if err != nil {
		t.Errorf("want no error, got %s", err)
	}

}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:12,代码来源:flags_test.go


示例9: runWithArgs

func runWithArgs(args ...string) error {
	opts := &options{}
	if _, err := gflags.ParseArgs(opts, args); err != nil {
		if flagErr, ok := err.(*gflags.Error); ok && flagErr.Type == gflags.ErrHelp {
			os.Exit(0)
		}
		return fmt.Errorf("could not parse options: %v", err)
	}
	if err := validateOptions(opts); err != nil {
		return fmt.Errorf("invalid options: %v", err)
	}

	return runWithOptions(opts)
}
开发者ID:saj1th,项目名称:go-torch,代码行数:14,代码来源:main.go


示例10: TestCoreLoopOncePosixExitHandling

func TestCoreLoopOncePosixExitHandling(t *testing.T) {
	testone := func(arguments string) (error, monitoringResult) {
		logbuf := func(t *testing.T, buf *bytes.Buffer) {
			if buf.Len() > 0 {
				t.Log(buf.String())
			}
		}

		var output bytes.Buffer
		defer logbuf(t, &output)
		log.SetOutput(&output)
		defer log.SetOutput(&bytes.Buffer{})

		oldopts := opts
		defer func() { opts = oldopts }()

		args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
		if err != nil {
			t.Fatal(err)
		}

		err = validateOptionConstraints()
		if err != nil {
			t.Fatal(err)
		}

		var logstream bytes.Buffer
		defer logbuf(t, &logstream)

		err = CoreLoopOnce(args, &logstream)
		code, _ := error2exit(err)

		return err, code
	}

	for i := 1; i < 256; i++ {
		err, code := testone(fmt.Sprintf("-- ./testdata/exit_with_code.sh %d", i))
		if code != monitorCritical {
			t.Errorf("want CRITICAL monitoring state for exit code %d, got %s due to err = %v", i, code, err)
		}
	}

	for i := monitorOk; i <= monitorUnknown; i++ {
		err, code := testone(fmt.Sprintf("--wrap-nagios-plugin -- ./testdata/exit_with_code.sh %d", i))
		if code != i {
			t.Errorf("want %s monitoring state, got %s due to err = %v", i, code, err)
		}
	}
}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:49,代码来源:core_test.go


示例11: main

func main() {
	var opts struct {
		CountryDBPath string `short:"f" long:"country-db" description:"Path to GeoIP country database" value-name:"FILE" default:""`
		CityDBPath    string `short:"c" long:"city-db" description:"Path to GeoIP city database" value-name:"FILE" default:""`
		Listen        string `short:"l" long:"listen" description:"Listening address" value-name:"ADDR" default:":8080"`
		ReverseLookup bool   `short:"r" long:"reverse-lookup" description:"Perform reverse hostname lookups"`
		PortLookup    bool   `short:"p" long:"port-lookup" description:"Enable port lookup"`
		Template      string `short:"t" long:"template" description:"Path to template" default:"index.html"`
		IPHeader      string `short:"H" long:"trusted-header" description:"Header to trust for remote IP, if present (e.g. X-Real-IP)"`
	}
	_, err := flags.ParseArgs(&opts, os.Args)
	if err != nil {
		os.Exit(1)
	}

	oracle := api.NewOracle()
	if opts.ReverseLookup {
		log.Println("Enabling reverse lookup")
		oracle.EnableLookupAddr()
	}
	if opts.PortLookup {
		log.Println("Enabling port lookup")
		oracle.EnableLookupPort()
	}
	if opts.CountryDBPath != "" {
		log.Printf("Enabling country lookup (using database: %s)", opts.CountryDBPath)
		if err := oracle.EnableLookupCountry(opts.CountryDBPath); err != nil {
			log.Fatal(err)
		}
	}
	if opts.CityDBPath != "" {
		log.Printf("Enabling city lookup (using database: %s)", opts.CityDBPath)
		if err := oracle.EnableLookupCity(opts.CityDBPath); err != nil {
			log.Fatal(err)
		}
	}
	if opts.IPHeader != "" {
		log.Printf("Trusting header %s to contain correct remote IP", opts.IPHeader)
	}

	api := api.New(oracle)
	api.Template = opts.Template
	api.IPHeader = opts.IPHeader

	log.Printf("Listening on %s", opts.Listen)
	if err := api.ListenAndServe(opts.Listen); err != nil {
		log.Fatal(err)
	}
}
开发者ID:TheBigBear,项目名称:ifconfigd,代码行数:49,代码来源:main.go


示例12: TestCoreLoopOnceExitSuccess

func TestCoreLoopOnceExitSuccess(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "-- true"
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	log.SetOutput(&output)

	err = CoreLoopOnce(args, &bytes.Buffer{})
	t.Log(output.String())
	if err != nil {
		t.Error("want no error, got", err)
	}
}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:19,代码来源:core_test.go


示例13: main

func main() {
	_, err := flags.ParseArgs(&opts, os.Args)
	PanicIf(err)

	m := martini.Classic()
	m.Map(SetupDB())

	// Serve static files from "static" directory.
	StaticOptions := martini.StaticOptions{Prefix: "static"}
	m.Use(martini.Static(opts.StaticDir, StaticOptions))

	// Render html templates from "templates" directory.
	m.Use(render.Renderer(render.Options{Directory: opts.TemplatesDir}))

	m.Get("/", IndexHandler)
	m.Post("/subscribe/", binding.Form(Subscription{}), SubscribeHandler)

	m.Run()
}
开发者ID:volodymyr-nakvasiuk,项目名称:website,代码行数:19,代码来源:server.go


示例14: TestCoreLoopRetryExitSuccessFunnyExitCodes

func TestCoreLoopRetryExitSuccessFunnyExitCodes(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--retries=3 --monitor-ok=1 -- false"
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	log.SetOutput(&output)

	err = CoreLoopRetry(args, &bytes.Buffer{})
	t.Log(output.String())
	if err != nil {
		t.Error("want no error, got", err)
	}
}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:19,代码来源:core_test.go


示例15: parseFlags

func parseFlags(flags interface{}, args []string) []string {
	args, err := goflags.ParseArgs(flags, args)
	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)
	}
	return args
}
开发者ID:Cygnusfear,项目名称:nulpunt,代码行数:19,代码来源:flags.go


示例16: parseArgs

// Parses the command-line arguments, and validates them.
func parseArgs(args []string) (opts *AppConfig, err error) {
	opts = &AppConfig{}

	_, err = goflags.ParseArgs(opts, args)
	if err != nil {
		return
	}

	// fix bad values...
	if opts.Clients < MIN_LOAD {
		opts.Clients = MIN_LOAD
	}

	if opts.Duration < MIN_RUN_TIME {
		opts.Duration = MIN_RUN_TIME
	}

	opts.d = time.Duration(opts.Duration) * time.Second
	return
}
开发者ID:politician,项目名称:knock,代码行数:21,代码来源:args.go


示例17: TestDuplicateExitCodes

func TestDuplicateExitCodes(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--monitor-ok=2 --monitor-warning=4 --monitor-critical=2 -- true"
	_, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	err = validateOptionConstraints()
	if err == nil {
		t.Error("want error, got nil")
	} else if e, ok := err.(*FlagConstraintError); ok {
		want := "is already considered"
		if !strings.Contains(e.Constraint, want) {
			t.Errorf("want %s, got %s", want, err)
		} else {
			t.Log("got", err)
		}
	} else {
		t.Error("want flag constraint error, got", err)
	}
}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:20,代码来源:flags_test.go


示例18: TestTooBigMaxDelay

func TestTooBigMaxDelay(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--timeout=1s --max-start-delay=2s -- true"
	_, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	err = validateOptionConstraints()
	if err == nil {
		t.Error("want error, got nil")
	} else if e, ok := err.(*FlagConstraintError); ok {
		want := "max delay >= timeout, no time left for actual command execution"
		if e.Constraint != want {
			t.Errorf("want %s, got %s", want, err)
		} else {
			t.Log("got", err)
		}
	} else {
		t.Error("want flag constraint error, got", err)
	}

}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:21,代码来源:flags_test.go


示例19: TestCoreLoopOnceWrongCommand

func TestCoreLoopOnceWrongCommand(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "-- /var/run/nonexistant"
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	log.SetOutput(&output)

	err = CoreLoopOnce(args, &bytes.Buffer{})
	t.Log(output.String())
	if err == nil {
		t.Error("want error, got nil")
	} else if _, ok := err.(*NotAvailableError); ok {
		t.Log("got", err)
	} else {
		t.Error("want not available error, got", err)
	}
}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:23,代码来源:core_test.go


示例20: TestCoreLoopOnceSoftTimeout

func TestCoreLoopOnceSoftTimeout(t *testing.T) {
	oldopts := opts
	defer func() { opts = oldopts }()

	arguments := "--timeout=100ms --grace-time=50ms -- sleep 1"
	args, err := flags.ParseArgs(&opts, strings.Fields(arguments))
	if err != nil {
		t.Fatal(err)
	}

	var output bytes.Buffer
	log.SetOutput(&output)

	err = CoreLoopOnce(args, &bytes.Buffer{})
	t.Log(output.String())
	if err == nil {
		t.Error("want error, got nil")
	} else if timeout, ok := err.(*TimeoutError); ok && timeout.soft {
		t.Log("got", err)
	} else {
		t.Error("want soft timeout error, got ", err)
	}
}
开发者ID:Jimdo,项目名称:periodicnoise,代码行数:23,代码来源:core_test.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang testfs.FileSystem类代码示例发布时间:2022-05-23
下一篇:
Golang go-flags.Parse函数代码示例发布时间: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