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

Golang flag.String函数代码示例

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

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



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

示例1: main

func main() {
	laddr := flag.String("listen", ":8001", "listen address")
	baddr := flag.String("backend", "127.0.0.1:1234", "backend address")
	secret := flag.String("secret", "the answer to life, the universe and everything", "tunnel secret")
	tunnels := flag.Uint("tunnels", 1, "low level tunnel count, 0 if work as server")
	flag.Int64Var(&tunnel.Timeout, "timeout", 10, "tunnel read/write timeout")
	flag.UintVar(&tunnel.LogLevel, "log", 1, "log level")

	flag.Usage = usage
	flag.Parse()

	app := &tunnel.App{
		Listen:  *laddr,
		Backend: *baddr,
		Secret:  *secret,
		Tunnels: *tunnels,
	}
	err := app.Start()
	if err != nil {
		fmt.Fprintf(os.Stderr, "start failed:%s\n", err.Error())
		return
	}
	go handleSignal(app)

	app.Wait()
}
开发者ID:xiaobodu,项目名称:gotunnel,代码行数:26,代码来源:main.go


示例2: main

func main() {
	help := flag.Bool("help", false, "Show usage")
	username := flag.String("u", "", "Specify Github user")
	password := flag.String("p", "", "Specify Github password")

	flag.Usage = func() {
		fmt.Printf("Usage:\n")
		flag.PrintDefaults()
	}
	flag.Parse()

	if *help == true || *username == "" || *password == "" {
		flag.Usage()
		return
	}

	ghc, err := ghclient.NewGithubClient(*username, *password, ghclient.AUTH_USER_PASSWORD)

	gistsc := ghgists.NewGists(ghc)

	res, err := gistsc.GetPublicGistsList()

	jr, err := res.Json()

	fmt.Printf("JSON: %v\nERROR: %v\n", jr, err)

	print("\n\nLOADING NEXT PAGE...\n\n")
	res, err = res.GetNextPage()

	jr, err = res.Json()

	fmt.Printf("JSON: %v\nERROR: %v\n", jr, err)
}
开发者ID:alcacoop,项目名称:go-github-client,代码行数:33,代码来源:main.go


示例3: 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


示例4: init

func init() {
	condition = flag.String("condition", "<ID>", "Condition ID, set only to check a single alert (optional)")
	stream = flag.String("stream", "<ID>", "Stream ID (mandatory)")
	api_url = flag.String("url", "http://localhost:12900", "URL to Graylog2 api (optional)")
	user = flag.String("user", "<username>", "API username (mandatory)")
	pass = flag.String("password", "<password>", "API password (mandatory)")
}
开发者ID:aanriot,项目名称:check-graylog2-stream,代码行数:7,代码来源:check-graylog2-stream.go


示例5: main

func main() {
	introText := "SIMPLE TWITTER REFORMATTER \n (╯°□°)╯︵ ┻━┻) \n"
	fmt.Printf(introText)

	key := flag.String("key", "nokey", "Twitter consumer key")
	secret := flag.String("sec", "nosecret", "Twitter consumer secret")
	debug := flag.Bool("debug", false, "Debug logging level")
	numTweets := flag.Int("num", 3, "Number of tweets to retrieve")

	flag.Parse()

	access_token, err := getBearerToken(*key, *secret, *debug)
	if err != nil || access_token == "" {
		log.Fatal("Could not retrieve token to make twitter API request")
		os.Exit(1)
	}

	// Create a very basic channel with tweets getting passed into the expander
	// Wait for it to finish executing before quiting.
	var tweetChannel chan string = make(chan string)
	var wg sync.WaitGroup
	wg.Add(1)
	go tweetRetriever(access_token, *numTweets, tweetChannel, &wg, *debug)
	go textExpander(tweetChannel)
	wg.Wait()
}
开发者ID:zachgoldstein,项目名称:go-test-app,代码行数:26,代码来源:plan.go


示例6: main

func main() {
	rand.Seed(time.Now().UTC().UnixNano())
	bind := flag.String("bind", ":8000", "The network ([ip]:port) to bind on.")
	addr := flag.String("addr", "", "The public address (host[:port]) of this node.")
	ephemeral := flag.Bool("ephemeral", false, "Use a process-local in-memory userless database. Can only be enabled in joint mode.")
	flag.Parse()

	if *ephemeral && *addr != "" {
		log.Fatal("-ephemeral cannot be used with -addr. Running as a part of a cluster requires coordination through a database.")
	}

	ctx := Context{
		Database:        NewAnonDatabase(),
		SecureKey:       []byte("12345678901234567890123456789012"),
		StreamKeepAlive: 10 * time.Second,
	}
	if !*ephemeral {
		var err error
		if ctx.Database, err = NewSQLDatabase(*addr, "sqlite3", "development.db"); err != nil {
			log.Fatal("Could not connect to database: ", err)
		}
	}

	mux := http.NewServeMux()
	mux.Handle("/static/", http.FileServer(disallowDirectoryListing(".")))
	mux.Handle("/stream/", UnsafeHandler{NewRetransmissionHandler(&ctx)})
	mux.Handle("/", UnsafeHandler{NewUIHandler(&ctx)})
	log.Fatal(http.ListenAndServe(*bind, mux))
}
开发者ID:pyos,项目名称:webmcast,代码行数:29,代码来源:main.go


示例7: main

func main() {
	var statsdHost = flag.String("statsd_host", "127.0.0.1", "Statsd host")
	var statsdPort = flag.Int("statsd_port", 8125, "Statsd host")
	var nodename = flag.String("nodename", "riak", "Riak node name")
	var riakHost = flag.String("riak_host", "127.0.0.1", "Riak host")
	var riakHttpPort = flag.Int("riak_http_port", 8098, "Riak HTTP port")
	flag.Parse()

	// First ping to node to make sure it works
	err := pingRiak(*riakHost, *riakHttpPort)
	if err != nil {
		log.Fatalf("Error: %v", err)
		os.Exit(1)
	}
	statsd := fmt.Sprintf("%s:%d", *statsdHost, *statsdPort)
	addr, err := net.ResolveUDPAddr("udp", statsd)
	if err != nil {
		log.Fatalf("Couldn't resolve UDP addr: %v", err)
		os.Exit(1)
	}
	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		log.Fatalf("Couldn't connect to statsd at %s", statsd)
		os.Exit(1)
	}

	// every 60s run hit the stats endpoint and then send to statsd
	interval := time.NewTicker(time.Second * 60)
	for _ = range interval.C {
		go getAndSendRiakMetrics(conn, *nodename, *riakHost, *riakHttpPort)
	}
}
开发者ID:jjmalina,项目名称:riak-statsd,代码行数:32,代码来源:main.go


示例8: main

func main() {
	var (
		listenAddress = flag.String("web.listen-address", ":9107", "Address to listen on for web interface and telemetry.")
		metricsPath   = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
		consulServer  = flag.String("consul.server", "localhost:8500", "HTTP API address of a Consul server or agent.")
		kvPrefix      = flag.String("kv.prefix", "", "Prefix from which to expose key/value pairs.")
		kvFilter      = flag.String("kv.filter", ".*", "Regex that determines which keys to expose.")
	)
	flag.Parse()

	exporter := NewExporter(*consulServer, *kvPrefix, *kvFilter)
	prometheus.MustRegister(exporter)

	log.Infof("Starting Server: %s", *listenAddress)
	http.Handle(*metricsPath, prometheus.Handler())
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
             <head><title>Consul Exporter</title></head>
             <body>
             <h1>Consul Exporter</h1>
             <p><a href='` + *metricsPath + `'>Metrics</a></p>
             </body>
             </html>`))
	})
	log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
开发者ID:clarenceb,项目名称:consul_exporter,代码行数:26,代码来源:consul_exporter.go


示例9: main

func main() {
	if docker.SelfPath() == "/sbin/init" {
		// Running in init mode
		docker.SysInit()
		return
	}
	// FIXME: Switch d and D ? (to be more sshd like)
	flDaemon := flag.Bool("d", false, "Daemon mode")
	flDebug := flag.Bool("D", false, "Debug mode")
	bridgeName := flag.String("b", "", "Attach containers to a pre-existing network bridge")
	pidfile := flag.String("p", "/var/run/docker.pid", "File containing process PID")
	flag.Parse()
	if *bridgeName != "" {
		docker.NetworkBridgeIface = *bridgeName
	} else {
		docker.NetworkBridgeIface = docker.DefaultNetworkBridge
	}
	if *flDebug {
		os.Setenv("DEBUG", "1")
	}
	docker.GIT_COMMIT = GIT_COMMIT
	if *flDaemon {
		if flag.NArg() != 0 {
			flag.Usage()
			return
		}
		if err := daemon(*pidfile); err != nil {
			log.Fatal(err)
		}
	} else {
		if err := runCommand(flag.Args()); err != nil {
			log.Fatal(err)
		}
	}
}
开发者ID:neomantra,项目名称:docker,代码行数:35,代码来源:docker.go


示例10: main

func main() {
	rpcAddr := flag.String("rpcaddr", ":1115", "rpc listen address")
	httpAddr := flag.String("httpaddr", ":8080", "http frontend listen address")
	flag.Parse()
	var s Server
	f, err := NewHTTPFrontend(*httpAddr)
	if err != nil {
		log.Fatal(err)
	}
	s.HTTPFrontend = f
	rpcplus.Register(&Router{s})
	rpcplus.HandleHTTP()
	go http.ListenAndServe(*rpcAddr, nil)

	d, err := discover.NewClient()
	if err != nil {
		log.Fatal(err)
	}
	if hostPort := strings.SplitN(*rpcAddr, ":", 2); hostPort[0] != "" {
		err = d.RegisterWithHost("flynn-strowger-rpc", hostPort[0], hostPort[1], nil)
	} else {
		err = d.Register("flynn-strowger-rpc", hostPort[1], nil)
	}
	if err != nil {
		log.Fatal(err)
	}

	s.ListenAndServe(nil)
}
开发者ID:pombredanne,项目名称:strowger,代码行数:29,代码来源:server.go


示例11: main

func main() {
	host := flag.String("h", "http://127.0.0.1:8086", "url to influxdb http api")
	dev := flag.Int("v", 100, "amount to modify previous value each step")
	database := flag.String("d", "testdata", "influxdb database")
	prefix := flag.String("p", "sampledata_", "metric prefix")
	metric := flag.String("m", "random-data", "name of metric")
	flag.Parse()

	var tel = telemetry.New(*prefix, (10 * time.Second))
	var reporter = reporters.InfluxReporter{
		Host:     *host,
		Interval: (30 * time.Second),
		Tel:      tel,
		Database: *database,
	}
	reporter.Report()

	var sample = telemetry.NewAverage(tel, *metric, (60 * time.Second))
	var val = 100
	var add = 0
	for {
		add = rand.Intn(*dev) - (*dev / 2)
		if val+add > 0 {
			val = val + add
		}
		sample.Add(tel, float64(val))
		fmt.Printf("added point %v \n", val)
		time.Sleep(3 * time.Second)
	}
}
开发者ID:arussellsaw,项目名称:influxdb-sampledata,代码行数:30,代码来源:main.go


示例12: main

func main() {
	c2bPort := flag.String("-c2b", "7000", "-c2b=portno.Default=7000")
	conf := flag.String("-conf", "config", "-conf=/path/to/conf. Default=./config")
	flag.Parse()

	config := parseConf(*conf)
	fmt.Println("Config:\n", config.ToString())

	var enabledAPIS []api
	for _, v := range config.EnabledAPIS {
		if v == "c2b" {
			enabledAPIS = append(enabledAPIS, c2b.NewAPI(*c2bPort, config))
		}
	}

	fmt.Println("Starting:", config.EnabledAPIS)
	startAPIS(enabledAPIS...)

	serve := make(chan os.Signal)
	signal.Notify(serve, syscall.SIGINT, syscall.SIGTERM) //Submit to user demands to quit, but gracefully yee sir.

	<-serve
	//graceful
	stopAPIS(enabledAPIS...)

}
开发者ID:Raphaeljunior,项目名称:mock-pesa,代码行数:26,代码来源:main.go


示例13: main

func main() {
	header := "-------------------------------------------------------------------------------\n        RRDA (RRDA REST DNS API) 1.01 (c) by Frederic Cambus 2012-2014\n-------------------------------------------------------------------------------"

	host := flag.String("host", "127.0.0.1", "Set the server host")
	port := flag.String("port", "8080", "Set the server port")

	flag.Usage = func() {
		fmt.Println(header)
		fmt.Println("\nUSAGE :")
		flag.PrintDefaults()
	}
	flag.Parse()

	fmt.Println(header)

	fmt.Println("\nListening on :", *host+":"+*port)

	m := pat.New()
	m.Get("/:server/x/:ip", http.HandlerFunc(ptr))
	m.Get("/:server/:domain/:querytype", http.HandlerFunc(query))

	if err := http.ListenAndServe(*host+":"+*port, m); err != nil {
		fmt.Println("\nERROR :", err)
		os.Exit(1)
	}
}
开发者ID:onceking,项目名称:rrda,代码行数:26,代码来源:rrda.go


示例14: main

func main() {

	data := flag.String("d", "", "Data file")
	template := flag.String("t", "", "Template file")
	flag.Parse()

	if len(*template) == 0 {
		usage()
	}

	var raw []byte
	var err error
	if len(*data) == 0 {
		raw, err = ioutil.ReadAll(os.Stdin)
		if err != nil || len(raw) == 0 {
			usage()
		}
	} else {
		raw, err = ioutil.ReadFile(*data)
		if err != nil || len(raw) == 0 {
			log.Fatal("Could not load file", err)
		}
	}

	var parsed interface{}
	err = json.Unmarshal(raw, &parsed)
	if err != nil {
		log.Fatal("Failed to parse JSON file ", err)
	}

	fmt.Println(mustache.RenderFile(*template, parsed))
}
开发者ID:hobbs,项目名称:mustache,代码行数:32,代码来源:gostash.go


示例15: main

func main() {
	optHost := flag.String("host", "localhost", "Hostname")
	optPort := flag.String("port", "8983", "Port")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	solr := SolrPlugin{
		Protocol: "http",
		Host:     *optHost,
		Port:     *optPort,
		Prefix:   "solr",
	}

	solr.BaseURL = fmt.Sprintf("%s://%s:%s/solr", solr.Protocol, solr.Host, solr.Port)
	solr.loadStats()

	helper := mp.NewMackerelPlugin(solr)

	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = fmt.Sprintf("/tmp/mackerel-plugin-%s-%s-%s", solr.Prefix, *optHost, *optPort)
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}
开发者ID:tjinjin,项目名称:mackerel-agent-plugins,代码行数:30,代码来源:solr.go


示例16: main

func main() {
	fmt.Printf("hyperion-dashboard%s\n", buildVersion)

	httpAddr := flag.String("http-address", "127.0.0.1:12300", "<addr>:<port> to listen on")
	dsn := flag.String("db", "", "Database source name")
	flag.Parse()

	dataSource := *dsn
	if dataSource == "" {
		if os.Getenv("HYPERION_DB") != "" {
			dataSource = os.Getenv("HYPERION_DB")
		}
	}

	if dataSource == "" {
		flag.Usage()
		log.Fatal("--db or HYPERION_DB not found")
	}

	db, err := NewDBConn(dataSource)
	if err != nil {
		log.Fatal(err.Error())
	}

	router := mux.NewRouter()
	router.HandleFunc("/", db.RecordsHandler)

	recovery := negroni.NewRecovery()
	logger := negroni.NewLogger()

	n := negroni.New(recovery, logger)
	n.UseHandler(router)
	n.Run(*httpAddr)
}
开发者ID:Tuxuri,项目名称:hyperion-dashboard,代码行数:34,代码来源:main.go


示例17: main

func main() {
	host := flag.String("url", "127.0.0.1", "Monitor server")
	appId := flag.String("appId", "", "App id")
	l := flag.String("l", "INFO", "Log level: TRACE, INFO")

	flag.Parse()

	var traceHandle io.Writer
	if *l == "TRACE" {
		traceHandle = os.Stdout
	} else {
		traceHandle = ioutil.Discard
	}
	InitLog(traceHandle, os.Stdout, os.Stdout, os.Stderr)

	Info.Println("Start agent with host =", *host, " and appId =", *appId, " and period 5 sec")

	do := func() {
		cpu, mem, err := getMesosMetrics()
		if err != nil {
			Error.Println("Load metrics error", err)
			return
		}
		Trace.Println("CPU: ", cpu)
		Trace.Println("Memory:", mem)

		sendData(*host, *appId, cpu, cpu, mem)
	}
	schedule(5, do)
	WaitCtrlC()
}
开发者ID:dataart-telco,项目名称:juju-charms,代码行数:31,代码来源:monitor-agent.go


示例18: main

func main() {
	var (
		listenAddress = flag.String("listen-address", ":9120", "Address to listen on for web interface and telemetry.")
		metricsPath   = flag.String("metric-path", "/metrics", "Path under which to expose metrics.")
		apiURL        = flag.String("api-url", "http://localhost:8001/", "Base-URL of PowerDNS authoritative server/recursor API.")
		apiKey        = flag.String("api-key", "", "PowerDNS API Key")
	)
	flag.Parse()

	hostURL, err := url.Parse(*apiURL)
	if err != nil {
		log.Fatalf("Error parsing api-url: %v", err)
	}

	server, err := getServerInfo(hostURL, *apiKey)
	if err != nil {
		log.Fatalf("Could not fetch PowerDNS server info: %v", err)
	}

	exporter := NewExporter(*apiKey, server.DaemonType, hostURL)
	prometheus.MustRegister(exporter)

	log.Infof("Starting Server: %s", *listenAddress)
	http.Handle(*metricsPath, prometheus.Handler())
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`<html>
             <head><title>PowerDNS Exporter</title></head>
             <body>
             <h1>PowerDNS Exporter</h1>
             <p><a href='` + *metricsPath + `'>Metrics</a></p>
             </body>
             </html>`))
	})
	log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
开发者ID:janeczku,项目名称:powerdns_exporter,代码行数:35,代码来源:powerdns_exporter.go


示例19: main

func main() {
	optHost := flag.String("host", "127.0.0.1", "Hostname")
	optPort := flag.String("port", "6379", "port")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	optDB := flag.String("db", "0", "Database")
	optNamespace := flag.String("namespace", "", "Namespace")
	flag.Parse()

	var sidekiq SidekiqPlugin
	sidekiq.Target = *optHost + ":" + *optPort
	sidekiq.Database = *optDB
	sidekiq.Namespace = *optNamespace
	helper := mp.NewMackerelPlugin(sidekiq)

	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = "/tmp/mackerel-plugin-sidekiq-" + *optHost + "-" + *optPort
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}
开发者ID:vasilyjp,项目名称:mackerel-plugin-sidekiq,代码行数:26,代码来源:sidekiq.go


示例20: main

func main() {

	// You should pass in your client key and secret key as args.
	// Or you can set your access key and secret key by replacing the default values below (2nd input param in flag.String)
	githubClientKey := flag.String("client_key", "[your github client key]", "your oauth client key")
	githubSecretKey := flag.String("secret_key", "[your github secret key]", "your oauth secret key")
	flag.Parse()

	// set the auth parameters
	auth.Config.CookieSecret = []byte("7H9xiimk2QdTdYI7rDddfJeV")
	auth.Config.LoginSuccessRedirect = "/private2"
	auth.Config.CookieSecure = false

	// login handler
	githubHandler := auth.Github(*githubClientKey, *githubSecretKey, "")
	http.Handle("/auth/login", githubHandler)

	// logout handler
	http.HandleFunc("/auth/logout", Logout)

	// public urls
	http.HandleFunc("/", Public)

	// private, secured urls
	http.HandleFunc("/private1", auth.SecureFunc(Private1))
	http.HandleFunc("/private2", auth.SecureUser(Private2))

	println("github demo starting on port 8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println(err)
	}
}
开发者ID:navy1125,项目名称:go.auth,代码行数:33,代码来源:github_demo.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang flag.StringVar函数代码示例发布时间:2022-05-24
下一篇:
Golang flag.Set函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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