本文整理汇总了Golang中flag.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Parse函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: main
func main() {
flag.Parse()
if len(os.Args) < 3 {
usage()
return
}
flag.Parse()
err := generateXLSXFromCSV(*csvPath, *xlsxPath, *delimiter)
if err != nil {
fmt.Printf(err.Error())
return
}
}
开发者ID:tealeg,项目名称:csv2xlsx,代码行数:13,代码来源:main.go
示例17: main
func main() {
flag.Parse()
var error error
if len(os.Args) < 3 {
usage()
return
}
flag.Parse()
error = generateCSVFromXLSXFile(*xlsxPath, *sheetIndex, func(s string) { fmt.Printf("%s", s) })
if error != nil {
fmt.Printf(error.Error())
return
}
}
开发者ID:hlife,项目名称:xlsx2csv,代码行数:14,代码来源:main.go
示例18: main
func main() {
var loop int
var file string
var mode string
var model string
var lambda float64
var verbose bool
flag.IntVar(&loop, "l", 10, "number of iterations")
flag.Float64Var(&lambda, "c", 0.1, "regularization parameter")
flag.StringVar(&file, "f", "", "data file")
flag.StringVar(&mode, "m", "", "mode {learn, test}")
flag.StringVar(&model, "w", "", "model file")
flag.BoolVar(&verbose, "v", false, "verbose mode")
flag.Parse()
if file == "" {
panic("Data must be specified")
}
if mode == "learn" {
flag.Parse()
X, y := LoadFromFile(file)
p := NewAdaGrad(lambda, loop)
p.Fit(X, y)
SaveModel(p, model)
} else if mode == "test" {
p := LoadModel(model)
X_test, y_test := LoadFromFile(file)
num_corr := 0.
n := 0.
pred_y := []string{}
for i, X_i := range X_test {
pred_y_i := p.Predict(X_i)
pred_y = append(pred_y, pred_y_i)
if verbose {
fmt.Println(pred_y_i)
}
if pred_y_i == y_test[i] {
num_corr += 1
}
n += 1
}
acc := num_corr / n
confusionMatrix(y_test, pred_y)
fmt.Println("Acc:", acc)
} else {
panic("Invalid mode")
}
}
开发者ID:c4e8ece0,项目名称:goAdaGrad,代码行数:50,代码来源:main.go
示例19: init
func init() {
hooks = hook.Hooks{}
flag.Parse()
log.SetPrefix("[webhook] ")
log.SetFlags(log.Ldate | log.Ltime)
if !*verbose {
log.SetOutput(ioutil.Discard)
}
log.Println("version " + version + " starting")
// load and parse hooks
log.Printf("attempting to load hooks from %s\n", *hooksFilePath)
err := hooks.LoadFromFile(*hooksFilePath)
if err != nil {
if !*verbose && !*noPanic {
log.SetOutput(os.Stdout)
log.Fatalf("couldn't load any hooks from file! %+v\naborting webhook execution since the -verbose flag is set to false.\nIf, for some reason, you want webhook to start without the hooks, either use -verbose flag, or -nopanic", err)
}
log.Printf("couldn't load hooks from file! %+v\n", err)
} else {
log.Printf("loaded %d hook(s) from file\n", len(hooks))
for _, hook := range hooks {
log.Printf("\t> %s\n", hook.ID)
}
}
}
开发者ID:jszalkowski,项目名称:webhook,代码行数:34,代码来源:webhook_windows.go
示例20: main
func main() {
var filename string
var v bool
flag.StringVar(&filename, "cfg", "", "path to config file")
flag.BoolVar(&v, "v", false, "show version")
flag.Parse()
if v {
fmt.Println(version)
return
}
cfg, err := config.Load(filename)
if err != nil {
log.Fatalf("[FATAL] %s. %s", version, err)
}
log.Printf("[INFO] Runtime config\n" + toJSON(cfg))
log.Printf("[INFO] Version %s starting", version)
log.Printf("[INFO] Go runtime is %s", runtime.Version())
initRuntime(cfg)
initMetrics(cfg)
initBackend(cfg)
go watchBackend()
startAdmin(cfg)
startListeners(cfg.Listen, cfg.Proxy.ShutdownWait, newProxy(cfg))
registry.Default.Deregister()
}
开发者ID:cursesun,项目名称:fabio,代码行数:29,代码来源:main.go
注:本文中的flag.Parse函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论