當前位置: 首頁>>代碼示例>>Golang>>正文


Golang flag.Parse函數代碼示例

本文整理匯總了Golang中flag.Parse函數的典型用法代碼示例。如果您正苦於以下問題:Golang Parse函數的具體用法?Golang Parse怎麽用?Golang Parse使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Parse函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: main

func main() {
	certpath := flag.String("cert", "", "The path to a PEM certificate")
	keypath := flag.String("key", "", "The path to a PEM key")
	flag.Parse()
	if len(*certpath) == 0 || len(*keypath) == 0 {
		flag.PrintDefaults()
		return
	}
	ctx := gossl.NewContext(gossl.SSLv3Method())
	ctx.SetOptions(gossl.OpNoCompression)
	err := ctx.UsePrivateKeyFile(*keypath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	ctx.UseCertificateFile(*certpath, gossl.FileTypePem)
	if err != nil {
		panic(err)
	}
	l, err := net.Listen("tcp", ":8000")
	if err != nil {
		panic(err)
	}
	l, err = gossl.NewListener(l, ctx)
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, %q\n", html.EscapeString(r.URL.Path))
	})
	http.Serve(l, nil)

}
開發者ID:runcom,項目名稱:gossl,代碼行數:29,代碼來源:httpserver.go

示例2: main

func main() {
	flag.Parse()

	grpc.EnableTracing = true

	flag.Parse()
	lis, err := net.Listen("tcp", *port)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	grpcServer := grpc.NewServer()

	var downstreamClients []pb.PingClient
	for _, d := range strings.Split(*downstreams, ",") {
		if d == "" {
			continue
		}
		log.Println(d)
		conn, err := grpc.Dial(d, grpc.WithBlock())
		if err != nil {
			log.Fatalf("In here " + err.Error())
		}
		defer conn.Close()

		downstreamClients = append(downstreamClients, pb.NewPingClient(conn))
	}
	pb.RegisterPingServer(grpcServer, &pingServer{downstreams: downstreamClients})

	go grpcServer.Serve(lis)

	log.Fatal(http.ListenAndServe(*httpPort, nil))
}
開發者ID:tcolgate,項目名稱:test,代碼行數:32,代碼來源:main.go

示例3: main

func main() {
	if e := os.Getenv("DOOZER_URI"); e != "" {
		*uri = e
	}

	if e := os.Getenv("DOOZER_BOOT_URI"); e != "" {
		*buri = e
	}

	flag.Usage = usage
	flag.Parse()

	if *showHelp {
		usage()
		return
	}

	if *showVersion {
		fmt.Println("doozer", version)
		return
	}

	if flag.NArg() < 1 {
		fmt.Fprintf(os.Stderr, "%s: missing command\n", os.Args[0])
		usage()
		os.Exit(127)
	}

	cmd := flag.Arg(0)

	c, ok := cmds[cmd]
	if !ok {
		fmt.Fprintln(os.Stderr, "Unknown command:", cmd)
		usage()
		os.Exit(127)
	}

	os.Args = flag.Args()
	flag.Parse()

	if *showHelp {
		help(cmd)
		return
	}

	args := flag.Args()
	ft := reflect.TypeOf(c.f)
	if len(args) != ft.NumIn() {
		fmt.Fprintf(os.Stderr, "%s: wrong number of arguments\n", cmd)
		help(cmd)
		os.Exit(127)
	}

	vals := make([]reflect.Value, len(args))
	for i, s := range args {
		vals[i] = reflect.ValueOf(s)
	}
	fv := reflect.ValueOf(c.f)
	fv.Call(vals)
}
開發者ID:musicglue,項目名稱:doozer,代碼行數:60,代碼來源:doozer.go

示例4: main

func main() {
	logger := log.NewLogger()
	cfg := config.Default()
	flag.StringVar(&cfg.WSAddress, "ws", cfg.WSAddress, "Websocket address")
	flag.StringVar(&cfg.RESTAddress, "rest", cfg.RESTAddress, "REST address")
	flag.StringVar(&cfg.Origin, "o", cfg.Origin, "Origin URL")
	file := flag.String("config", "", "Config file")
	flag.Parse()
	if *file != "" {
		err := config.FromFile(*file, &cfg)
		if err != nil {
			logger.Err.Fatal(err)
		}
		flag.Parse()
	}
	broker := pubsub.NewBroker()
	go func() {
		wsRouter := mux.NewRouter()
		wsRouter.Handle("/{id}", handlers.WSHandler{Broker: broker, Config: cfg, Logger: logger})
		logger.Out.Println("Listening websockets on", cfg.WSAddress)
		logger.Err.Fatal(http.ListenAndServe(cfg.WSAddress, wsRouter))
	}()
	go func() {
		restRouter := mux.NewRouter()
		restRouter.Handle("/topic", handlers.List{Broker: broker, Logger: logger}).Methods("GET")
		restRouter.Handle("/topic", handlers.Add{Broker: broker, Logger: logger}).Methods("POST")
		restRouter.Handle("/topic/{id}", handlers.Pub{Broker: broker, Logger: logger}).Methods("POST")
		restRouter.Handle("/topic/{id}", handlers.Del{Broker: broker, Logger: logger}).Methods("DELETE")
		restRouter.Handle("/ping", handlers.Ping{Logger: logger}).Methods("GET")
		logger.Out.Println("Listening REST on", cfg.RESTAddress)
		logger.Err.Fatal(http.ListenAndServe(cfg.RESTAddress, restRouter))
	}()
	wait := make(chan struct{})
	<-wait
}
開發者ID:arvinkulagin,項目名稱:beeper,代碼行數:35,代碼來源:main.go

示例5: main

func main() {
	var action string

	// rewrite arguments so that we can support multiple "actions" in a single binary
	newArgs := make([]string, 0, len(os.Args))
	for i, arg := range os.Args {
		if i > 0 && arg[0] != '-' && action == "" {
			action = arg
			continue
		}

		newArgs = append(newArgs, arg)
	}
	os.Args = newArgs

	if action == "" {
		fmt.Fprintln(os.Stderr, "Error: action was not specified")
		dieWithUsage()
	}

	if action == ACTION_LOGS_COLLECTOR {
		logscol.InitFlags()
		flag.Parse()
		logscol.Run()
		return
	} else if action == ACTION_LOGS_PROCESSOR {
		logsproc.InitFlags()
		flag.Parse()
		logsproc.Run()
		return
	}

	dieWithUsage()
}
開發者ID:kshvakov,項目名稱:thunder,代碼行數:34,代碼來源:main.go

示例6: main

func main() {
	flag.Usage = help

	cmd := "help"
	switch av0 := path.Base(os.Args[0]); av0 {
	case "tao_run", "tao_list", "tao_stop", "tao_kill":
		cmd = av0[4:]
		flag.Parse()
	default:
		// Get options before the command verb
		flag.Parse()
		// Get command verb
		if flag.NArg() > 0 {
			cmd = flag.Arg(0)
		}
		// Get options after the command verb
		if flag.NArg() > 1 {
			flag.CommandLine.Parse(flag.Args()[1:])
		}
	}

	sockPath := path.Join(hostPath(), "admin_socket")
	conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: sockPath, Net: "unix"})
	options.FailIf(err, "Can't connect to host admin socket")
	defer conn.Close()

	client := tao.NewLinuxHostAdminClient(conn)
	switch cmd {
	case "help":
		help()
	case "run":
		runHosted(&client, flag.Args())
	case "stop":
		for _, s := range flag.Args() {
			var subprin auth.SubPrin
			_, err := fmt.Sscanf(s, "%v", &subprin)
			options.FailIf(err, "Not a subprin: %s", s)
			err = client.StopHostedProgram(subprin)
			options.FailIf(err, "Could not stop %s", s)
		}
	case "kill":
		for _, s := range flag.Args() {
			var subprin auth.SubPrin
			options.FailIf(err, "Not a subprin: %s", s)
			err = client.KillHostedProgram(subprin)
			options.FailIf(err, "Could not kill %s", s)
		}
	case "list":
		names, pids, err := client.ListHostedPrograms()
		options.FailIf(err, "Can't list hosted programs")
		for i, p := range pids {
			fmt.Printf("pid=%d subprin=%v\n", p, names[i])
		}
		fmt.Printf("%d hosted programs\n", len(pids))
	default:
		options.Usage("Unrecognized command: %s", cmd)
	}

	return
}
開發者ID:kevinawalsh,項目名稱:cloudproxy,代碼行數:60,代碼來源:tao_launch.go

示例7: main

func main() {
	var listenErr chan error
	flag.Var(&plines, "c", "Path to config, may be repeated")
	flag.Parse()

	if len(plines) == 0 {
		log.Fatal("No configs provided")
	}

	if *prometheusAddr != "" {
		if *loop == 0 {
			log.Fatal("Can only expose metrics in daemon mode")
		}
		http.Handle("/metrics", prometheus.Handler())
		go http.ListenAndServe(*prometheusAddr, nil)
	}
	if *debugEndpoint != "" {
		go func() {
			listenErr <- http.ListenAndServe(*debugEndpoint, nil)

		}()
	}

	for {
		for _, file := range plines {
			log.Print("# Running ", file)
			backupsTotal.WithLabelValues(file).Inc()
			pipe, err := pipeline.New(file)
			if err != nil {
				log.Printf("ERROR loading %s: %s", file, err)
				backupsFailed.WithLabelValues(file).Inc()
				continue
			}
			begin := time.Now()
			bytesWritten, err := pipe.Run()
			if err != nil {
				log.Printf("ERROR running %s: %s", file, err)
				backupsFailed.WithLabelValues(file).Inc()
				continue
			}
			backupSize.WithLabelValues(file).Set(float64(bytesWritten))

			now := time.Now()
			backupSeen.WithLabelValues(file).Set(float64(now.Unix()))
			backupDuration.WithLabelValues(file).Set(now.Sub(begin).Seconds())
		}
		if *loop == 0 {
			break
		}
		plines = pipelines{}
		log.Print("Sleeping for ", *loop)
		time.Sleep(*loop)
		flag.Parse() // We can do that nicer..
	}
	if *debugEndpoint != "" {
		log.Print("Debugging enabled, keep listening for debugging")
		log.Print(<-listenErr)
	}
}
開發者ID:discordianfish,項目名稱:byte-piper,代碼行數:59,代碼來源:main.go

示例8: main

func main() {
	flag.Parse()

	if *k%2 != 0 || *from < 1 || *to < 1 || *k < *from || *k < *to {
		log.Fatal("Invalid parameters", *from, *to, *k)
	}

	flag.Parse()
	if *cpuProfile != "" {
		f, err := os.Create(*cpuProfile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	routing.InstallRouting(*epoc)

	chrono := bh.NewApp("Chrono")
	ch := make(chan bool, 1024)
	cnt := 0
	rcvF := func(msg bh.Msg, ctx bh.RcvContext) error {
		if cnt++; cnt%1024 == 0 {
			ch <- true
		}
		return nil
	}
	mapF := func(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {
		return ctx.LocalMappedCells()
	}
	chrono.HandleFunc(routing.Advertisement{}, mapF, rcvF)

	start := time.Now()
	for p := *from; p <= *to; p++ {
		go func(p int) {
			if err := emitPod(p, *k); err != nil {
				panic(err)
			}
		}(p)
	}
	go func() {
		bh.Start()
		close(ch)
	}()

	finish := time.Now()
	for {
		select {
		case _, ok := <-ch:
			if !ok {
				return
			}
			finish = time.Now()
		case <-time.After(*idleTimeout):
			log.Printf("Took %v (%v-%v)", finish.Sub(start), start, finish)
		}
	}
}
開發者ID:jyzhe,項目名稱:beehive,代碼行數:59,代碼來源:main.go

示例9: InitTests

func InitTests(startIndexor bool) {
	if !hasStartedTesting {
		flag.Parse()
		hasStartedTesting = true
		flag.Parse()
		log.SetFlags(log.Ltime | log.Lshortfile)
		api.Domain = *eshost
	}
}
開發者ID:mschoch,項目名稱:elastigo,代碼行數:9,代碼來源:search_test.go

示例10: main

func main() {

	flag.Parse()
	args := flag.Args()
	fmt.Fprintf(os.Stderr, "\n")

	availableCommands := "Available commands:\n\n maketorrent\n info"

	if len(args) > 0 {
		switch args[0] {
		case "maketorrent":
			name := flag.String("name", "", "Torrent name, defaults to [file]+.torrent")
			announce := flag.String("announce", "udp://tracker.publicbt.com:80", "Tracker url")
			announceList := flag.String("announceList", "", "Comma seperated tracker urls")
			comment := flag.String("comment", "", "Optional comment")
			createdBy := flag.String("createdBy", "Tulva", "Author")
			encoding := flag.String("encoding", "UTF-8", "Encoding")

			flag.Parse()
			args = flag.Args()

			if len(args) == 1 {
				fmt.Fprintf(os.Stderr, "Usage: maketorrent [options] File\n\n")
				flag.PrintDefaults()
			} else if len(args) == 2 {
				clf := &CLFlags{
					Name:         *name,
					Announce:     *announce,
					AnnounceList: *announceList,
					Comment:      *comment,
					CreatedBy:    *createdBy,
					Encoding:     *encoding,
				}
				t := MakeTorrentFile(args[1], clf)
				fmt.Fprintf(os.Stderr, "Made torrent File: %s", t.Name())
			}
		case "info":
			name := flag.Bool("name", true, "Torrent name")
			if len(args) == 1 {
				fmt.Fprintf(os.Stderr, "Usage: info [options] File\n\n")
				flag.PrintDefaults()
			} else if len(args) == 2 {
				metaInfo := TorrentInfo(args[1])
				fmt.Fprintf(os.Stderr, "Info:\n\n")
				if *name {
					fmt.Fprintf(os.Stderr, "\tName: %s", metaInfo.info.name)
				}
			}
		default:
			fmt.Fprintf(os.Stderr, availableCommands)
		}
	} else {
		fmt.Fprintf(os.Stderr, availableCommands)
	}
	fmt.Fprintf(os.Stderr, "\n\n")
}
開發者ID:ramseydsilva,項目名稱:torrentutils,代碼行數:56,代碼來源:main.go

示例11: main

func main() {
	// Define our commandline flags:
	fs := flag.String("fs", ".", "Root directory of served files and templates")
	xrGifArg := flag.String("xrg", "", "X-Accel-Redirect header prefix for serving images or blank to disable")
	xrThumbArg := flag.String("xrt", "", "X-Accel-Redirect header prefix for serving thumbnails or blank to disable")

	fl_listen_uri := flag.String("l", "tcp://0.0.0.0:8080", "listen URI (schemes available are tcp, unix)")
	flag.Parse()

	// Parse all the URIs:
	listen_addr, err := base.ParseListenable(*fl_listen_uri)
	base.PanicIf(err)

	// Parse the flags and set values:
	flag.Parse()

	// Make directories we need:
	base_folder = base.CanonicalPath(path.Clean(*fs))
	os.MkdirAll(store_folder(), 0775)
	os.MkdirAll(thumb_folder(), 0775)
	os.MkdirAll(tmp_folder(), 0775)

	xrGif = *xrGifArg
	xrThumb = *xrThumbArg

	// Create/update the DB schema if needed:
	api, err := NewAPI()
	if err != nil {
		log.Fatal(err)
		return
	}
	api.Close()

	// Watch the html templates for changes and reload them:
	_, cleanup, err := web.WatchTemplates("ui", html_path(), "*.html", nil, &uiTmpl)
	if err != nil {
		log.Println(err)
		return
	}
	defer cleanup()

	// Start profiler:
	go func() {
		log.Println(http.ListenAndServe("localhost:6060", nil))
	}()

	// Start the server:
	_, err = base.ServeMain(listen_addr, func(l net.Listener) error {
		return http.Serve(l, web.ReportErrors(web.Log(web.DefaultErrorLog, web.ErrorHandlerFunc(requestHandler))))
	})
	if err != nil {
		log.Println(err)
		return
	}
}
開發者ID:JamesDunne,項目名稱:go-i-host,代碼行數:55,代碼來源:main.go

示例12: Parse

func (config *Config) Parse() error {
	flag.Parse()
	if config.Config != "" {
		err := config.parseConfigParamFile()
		if err != nil {
			return err
		}
	}
	flag.Parse()
	return nil
}
開發者ID:popeye17,項目名稱:pat,代碼行數:11,代碼來源:pat_config.go

示例13: init

func init() {
	flag.StringVar(&storage.LogRoot, "log-root", "/data/logs", "log path to store logs")
	// Support a legacy behavior that that allows default drain uri to be specified using a drain-uri
	// flag.
	flag.StringVar(&configurer.DefaultDrainURI, "drain-uri", "", "default drainURI, once set in etcd, this has no effect.")
	flag.Parse()
	// Set the default value for this AFTER the proper value of *publishInterval has been
	// established, since publishTTL should be twice the publishInterval by default.
	flag.IntVar(&publishTTL, "publish-ttl", *publishInterval*2, "publish TTL in seconds")
	// Now reparse flags in case the default publishTTL is overriden by a flag.
	flag.Parse()
}
開發者ID:CodeJuan,項目名稱:deis,代碼行數:12,代碼來源:main.go

示例14: main

func main() {
	flag.Parse()
	if len(os.Args) < 3 {
		flag.PrintDefaults()
		return
	}
	flag.Parse()
	printer := func(s string) { fmt.Printf("%s", s) }
	if err := generateCSVFromXLSXFile(*xlsxPath, *sheetIndex, printer); err != nil {
		fmt.Println(err)
	}
}
開發者ID:Espresson,項目名稱:xlsx2csv,代碼行數:12,代碼來源:main.go

示例15: main

func main() {
	flag.Usage = Usage
	flag.Parse()

	if *showHelp {
		Usage()
		return
	}

	if *showVersion {
		fmt.Println("doozer", doozer.Version)
		return
	}

	if flag.NArg() < 1 {
		fmt.Fprintf(os.Stderr, "%s: missing command\n", os.Args[0])
		Usage()
		os.Exit(127)
	}

	cmd := flag.Arg(0)

	c, ok := cmds[cmd]
	if !ok {
		fmt.Fprintln(os.Stderr, "Unknown command:", cmd)
		Usage()
		os.Exit(127)
	}

	os.Args = flag.Args()
	flag.Parse()

	if *showHelp {
		help(cmd)
		return
	}

	args := flag.Args()
	ft := reflect.Typeof(c.f).(*reflect.FuncType)
	if len(args) != ft.NumIn() {
		fmt.Fprintf(os.Stderr, "%s: wrong number of arguments\n", cmd)
		help(cmd)
		os.Exit(127)
	}

	vals := make([]reflect.Value, len(args))
	for i, s := range args {
		vals[i] = reflect.NewValue(s)
	}
	fv := reflect.NewValue(c.f).(*reflect.FuncValue)
	fv.Call(vals)
}
開發者ID:kr,項目名稱:doozer,代碼行數:52,代碼來源:doozer.go


注:本文中的flag.Parse函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。