本文整理匯總了Golang中flag.String函數的典型用法代碼示例。如果您正苦於以下問題:Golang String函數的具體用法?Golang String怎麽用?Golang String使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了String函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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()
}
示例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)
}
示例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)
}
示例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)")
}
示例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()
}
示例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))
}
示例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)
}
}
示例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))
}
示例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)
}
}
}
示例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)
}
示例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)
}
}
示例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...)
}
示例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)
}
}
示例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))
}
示例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()
}
}