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

Golang flag.Args函数代码示例

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

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



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

示例1: main

func main() {
	flag.Var(&patternVar, "pattern", "which add pattern")

	flag.Parse()

	patterns := []string{
		".DS_Store",
		".DS_Store?",
		"._*",
		".Spotlight-V100",
		".Trashes",
		"ehthumbs.db",
		"Thumbs.db",
	}

	if flag.NFlag() > 0 {
		for i := 0; i < len(patternVar); i++ {
			patterns = append(patterns, patternVar[i])
		}
	}

	if len(flag.Args()) == 0 {
		clean("./", patterns)
	} else {
		for _, args := range flag.Args() {
			clean(args, patterns)
		}
	}
}
开发者ID:gouvinb,项目名称:goclean,代码行数:29,代码来源:clean.go


示例2: main

func main() {
	password := flag.String("password", "", "Password for all redis instances")
	db := flag.Int("db", 0, "DB number")
	socket := flag.String("socket", "/tmp/redis-monitor.sock", "Socket to provide metrics over")
	flag.Parse()
	if len(flag.Args()) < 1 {
		flag.Usage()
		os.Exit(1)
	}
	s := &http.Server{
		Handler: &Addresses{
			Addr:     flag.Args(),
			Password: *password,
			DB:       int64(*db),
		},
	}

	l, err := util.CreateSocket(*socket)

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

	defer profile.Start(profile.MemProfile).Stop()

	if err != nil {
		panic(err)
	}

	if err := s.Serve(l); err != nil {
		panic(err)
	}
}
开发者ID:mehulsbhatt,项目名称:gollector-monitors,代码行数:33,代码来源:redis-monitor.go


示例3: main

func main() {
	var bindAddress string
	var port int

	flag.IntVar(&port, "port", 9125, "Port to listen on")
	flag.IntVar(&port, "p", 9125, "Port to listen on")

	flag.StringVar(&bindAddress, "bind", "0.0.0.0", "IP Address to listen on")
	flag.StringVar(&bindAddress, "b", "0.0.0.0", "IP Address to listen on")

	flag.StringVar(&prefix, "prefix", "statsrelay", "The prefix to use with self generated stats")

	flag.BoolVar(&verbose, "verbose", false, "Verbose output")
	flag.BoolVar(&verbose, "v", false, "Verbose output")

	flag.Parse()

	if len(flag.Args()) == 0 {
		log.Fatalf("One or most host specifications are needed to locate statsd daemons.\n")
	}

	hashRing = consistent.New()
	hashRing.NumberOfReplicas = 1

	for _, v := range flag.Args() {
		var addr *net.UDPAddr
		var err error
		host := strings.Split(v, ":")

		switch len(host) {
		case 1:
			log.Printf("Invalid statsd location: %s\n", v)
			log.Fatalf("Must be of the form HOST:PORT or HOST:PORT:INSTANCE\n")
		case 2:
			addr, err = net.ResolveUDPAddr("udp", v)
			if err != nil {
				log.Printf("Error parsing HOST:PORT \"%s\"\n", v)
				log.Fatalf("%s\n", err.Error())
			}
		case 3:
			addr, err = net.ResolveUDPAddr("udp", host[0]+":"+host[1])
			if err != nil {
				log.Printf("Error parsing HOST:PORT:INSTANCE \"%s\"\n", v)
				log.Fatalf("%s\n", err.Error())
			}
		default:
			log.Fatalf("Unrecongnized host specification: %s\n", v)
		}

		if addr != nil {
			udpAddr[v] = addr
			hashRing.Add(v)
		}
	}

	epochTime = time.Now().Unix()
	runServer(bindAddress, port)

	log.Printf("Normal shutdown.\n")
}
开发者ID:denen99,项目名称:statsrelay,代码行数:60,代码来源:statsrelay.go


示例4: main

func main() {
	defer util.Run()()
	var ring *pfring.Ring
	var err error
	if ring, err = pfring.NewRing(*iface, uint32(*snaplen), pfring.FlagPromisc); err != nil {
		log.Fatalln("pfring ring creation error:", err)
	}
	if len(flag.Args()) > 0 {
		bpffilter := strings.Join(flag.Args(), " ")
		fmt.Fprintf(os.Stderr, "Using BPF filter %q\n", bpffilter)
		if err = ring.SetBPFFilter(bpffilter); err != nil {
			log.Fatalln("BPF filter error:", err)
		}
	}
	if *cluster >= 0 {
		if err = ring.SetCluster(*cluster, pfring.ClusterType(*clustertype)); err != nil {
			log.Fatalln("pfring SetCluster error:", err)
		}
	}
	if err = ring.SetSocketMode(pfring.ReadOnly); err != nil {
		log.Fatalln("pfring SetSocketMode error:", err)
	} else if err = ring.Enable(); err != nil {
		log.Fatalln("pfring Enable error:", err)
	}
	dumpcommand.Run(ring)
}
开发者ID:dazer-chen,项目名称:gopacket,代码行数:26,代码来源:main.go


示例5: main

func main() {
	algo := flag.Int("a", 256, "SHA hash algorithm (one of 256, 384, or 512)")
	check := flag.Bool("c", false, "read SHA sums from the files and check them")
	hidden := flag.Bool("d", false, "sum hidden (dot) files")
	flag.Parse()

	progName = filepath.Base(os.Args[0])
	sumHidden = *hidden

	switch *algo {
	case 1:
		sumFunc = sum1
	case 256:
		sumFunc = sum256
	case 384:
		sumFunc = sum384
	case 512:
		sumFunc = sum512
	default:
		fmt.Println("Unrecognised algorithm.")
		os.Exit(1)
	}

	if *check {
		checkFile(flag.Args())
	} else {
		for _, root := range flag.Args() {
			err := filepath.Walk(root, walker)
			if err != nil {
				fmt.Printf("%v\n", err)
			}
		}
	}
}
开发者ID:postfix,项目名称:rshasum,代码行数:34,代码来源:sum.go


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


示例7: main

func main() {
	flag.Parse()
	var handle *pcap.Handle
	var err error
	if *fname != "" {
		if handle, err = pcap.OpenOffline(*fname); err != nil {
			log.Fatalln("PCAP OpenOffline error:", err)
		}
	} else {
		if handle, err = pcap.OpenLive(*iface, int32(*snaplen), true, time.Second); err != nil {
			log.Fatalln("PCAP OpenLive error:", err)
		}
		if *tstype != "" {
			if t, err := pcap.TimestampSourceFromString(*tstype); err != nil {
				log.Fatalf("Supported timestamp types: %v", handle.SupportedTimestamps())
			} else if err := handle.SetTimestampSource(t); err != nil {
				log.Fatalf("Supported timestamp types: %v", handle.SupportedTimestamps())
			}
		}
		if len(flag.Args()) > 0 {
			bpffilter := strings.Join(flag.Args(), " ")
			fmt.Fprintf(os.Stderr, "Using BPF filter %q\n", bpffilter)
			if err = handle.SetBPFFilter(bpffilter); err != nil {
				log.Fatalln("BPF filter error:", err)
			}
		}
	}
	dumpcommand.Run(handle)
}
开发者ID:jcantrill,项目名称:geard,代码行数:29,代码来源:main.go


示例8: main

func main() {
	flag.Parse()
	if len(flag.Args()) < 2 {
		flag.PrintDefaults()
		log.Fatalf("usage: chmod mode filepath")
	}

	octval, err := strconv.ParseUint(flag.Args()[0], 8, 32)
	if err != nil {
		log.Fatalf("Unable to decode mode. Please use an octal value. arg was %s, err was %v", flag.Args()[0], err)
	} else if octval > 0777 {
		log.Fatalf("Invalid octal value. Value larger than 777, was %o", octval)
	}

	mode := uint32(octval)

	var errors string
	for _, arg := range flag.Args()[1:] {
		if err := syscall.Chmod(arg, mode); err != nil {
			errors += fmt.Sprintf("Unable to chmod, filename was %s, err was %v\n", arg, err)
		}
	}
	if errors != "" {
		log.Fatalf(errors)
	}

}
开发者ID:u-root,项目名称:u-root,代码行数:27,代码来源:chmod.go


示例9: main

func main() {
	cbServ := flag.String("couchbase", "http://localhost:8091/",
		"URL to couchbase")
	cbBucket := flag.String("bucket", "default", "couchbase bucket")
	includeExt := flag.Bool("includeExt", false, "include file extension in document ID")
	verbose := flag.Bool("v", false, "verbose output")

	flag.Parse()

	b, err := couchbase.GetBucket(*cbServ, "default", *cbBucket)
	maybeFatal(err, "Error connecting to couchbase: %v\n", err)

	for _, filename := range flag.Args() {
		key := pathToID(filename, *includeExt)
		bytes, err := ioutil.ReadFile(filename)
		maybeFatal(err, "Error reading file contents: %v\n", err)
		b.SetRaw(key, 0, bytes)
		if *verbose {
			fmt.Printf("Loaded %s to key %s\n", filename, key)
		}
	}
	if *verbose {
		fmt.Printf("Loaded %d documents into bucket %s\n", len(flag.Args()), *cbBucket)
	}
}
开发者ID:jchris,项目名称:indexing,代码行数:25,代码来源:loadfile.go


示例10: main

func main() {
	flag.Parse()
	if *h || len(flag.Args()) == 0 {
		flag.Usage()
		return
	}

	root, err := url.Parse(*addr)
	if err != nil {
		log.Fatalf("Error parsing server address: %v", err)
	}

	destPath := flag.Args()[0]
	root.Path = path.Join(root.Path, destPath)

	if *write {
		doWrite(root)
	} else {
		res, err := http.Get(root.String())
		if err != nil {
			log.Fatalf("Error fetching from server: %v", err)
		}
		if res.StatusCode == 500 || res.StatusCode == 404 {
			log.Printf("Invalid status code %v", res.StatusCode)
			log.Printf("Status text: %v", res.Status)
			res.Body.Close()
			return
		} else {
			editFile(root, res.Body, *editor, flag.Args()[1:]...)
		}
	}
}
开发者ID:andrebq,项目名称:exp,代码行数:32,代码来源:main.go


示例11: getFileHandles

// getFileHandles uses our arguments to set up our input and output files
func getFileHandles() (in, out *os.File, err error) {
	// Input file should be our only command line argument
	if len(flag.Args()) != 1 {
		err = fmt.Errorf("Must have exactly one argument (input filename).  Received: %v",
			flag.Args())
		return
	}
	in, err = os.Open(flag.Arg(0))
	if err != nil {
		err = fmt.Errorf("Error: Unable to open input file %v: %v", flag.Arg(0),
			err)
		return
	}

	// Output file
	out = os.Stdout
	if *output != "-" {
		out, err = os.Create(*output)
		if err != nil {
			err = fmt.Errorf("Error: Unable to open output file %v: %v", *output,
				err)
			return
		}
	}

	return
}
开发者ID:CodeMonk,项目名称:GoSquareToShopify,代码行数:28,代码来源:main.go


示例12: main

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

	command := ""
	if flag.NArg() > 0 {
		command = flag.Arg(0)
		switch command {
		case "convert":
			if flag.NArg() <= 1 {
				fmt.Fprintln(os.Stderr, "missing cover profile")
				os.Exit(1)
			}
			if err := convertProfiles(flag.Args()[1:]...); err != nil {
				fmt.Fprintln(os.Stderr, "error:", err)
				os.Exit(1)
			}
		case "annotate":
			os.Exit(annotateSource())
		case "report":
			os.Exit(reportCoverage())
		case "test":
			if err := runTests(flag.Args()[1:]); err != nil {
				fmt.Fprintln(os.Stderr, "error:", err)
				os.Exit(1)
			}
		default:
			fmt.Fprintf(os.Stderr, "Unknown command: %#q\n\n", command)
			usage()
		}
	} else {
		usage()
	}
}
开发者ID:litixsoft,项目名称:lxb,代码行数:34,代码来源:main.go


示例13: main

func main() {
	var debugMode = flag.Bool("debug", false, "Enable debug messages")

	flag.Parse()

	if len(flag.Args()) != 1 {
		usage()
		os.Exit(1)
	}

	if *debugMode {
		enableDebugMode(*debugMode)
		InfoLogger.Print("Enabling debug messages")
	}

	config, err := parseConfig(flag.Args()[0])

	if err != nil {
		ErrorLogger.Printf("Error while parsing the configuration file: %s\n", err)
		os.Exit(1)
	}

	handler := NewProxyHandler(config)

	listenAddress := fmt.Sprintf("%s:%d", config.Server.Address, config.Server.Port)
	http.ListenAndServe(listenAddress, handler)
}
开发者ID:scalp42,项目名称:s3proxy,代码行数:27,代码来源:main.go


示例14: main

func main() {
	flag.Parse()
	// To see logs, use the -logtostderr flag and change the verbosity with
	// -v 0 (less verbose) up to -v 5 (more verbose).
	if len(flag.Args()) != 1 {
		fmt.Fprintf(os.Stderr, "Usage: %v <infohash>\n\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "Example infohash: %v\n", exampleIH)
		flag.PrintDefaults()
		os.Exit(1)
	}
	ih, err := dht.DecodeInfoHash(flag.Args()[0])
	if err != nil {
		fmt.Fprintf(os.Stderr, "DecodeInfoHash error: %v\n", err)
		os.Exit(1)
	}
	// Starts a DHT node with the default options. It picks a random UDP port. To change this, see dht.NewConfig.
	d, err := dht.New(nil)
	if err != nil {
		fmt.Fprintf(os.Stderr, "New DHT error: %v", err)
		os.Exit(1)

	}
	// For debugging.
	go http.ListenAndServe(fmt.Sprintf(":%d", httpPortTCP), nil)

	go d.Run()
	go drainresults(d)

	for {
		d.PeersRequest(string(ih), false)
		time.Sleep(5 * time.Second)
	}
}
开发者ID:hyg,项目名称:go.sample,代码行数:33,代码来源:main.go


示例15: main

func main() {
	flag.Parse()
	if len(flag.Args()) != 1 {
		log.Fatal("Usage: go run goprint.go path")
	}
	bpkg, err := build.Default.Import(flag.Args()[0], ".", 0)
	if err != nil {
		log.Fatal(err)
	}
	fset := token.NewFileSet()
	files := make(map[string]*ast.File)
	for _, fname := range bpkg.GoFiles {
		p, err := ioutil.ReadFile(filepath.Join(bpkg.SrcRoot, bpkg.ImportPath, fname))
		if err != nil {
			log.Fatal(err)
		}
		file, err := parser.ParseFile(fset, fname, p, parser.ParseComments)
		if err != nil {
			log.Fatal(err)
		}
		files[fname] = file
	}
	c := spew.NewDefaultConfig()
	c.DisableMethods = true
	apkg, _ := ast.NewPackage(fset, files, importer, nil)
	c.Dump(apkg)
	ast.Print(fset, apkg)
	dpkg := doc.New(apkg, bpkg.ImportPath, 0)
	c.Dump(dpkg)
}
开发者ID:maddyonline,项目名称:gddo,代码行数:30,代码来源:goprint.go


示例16: main

func main() {
	log.SetFlags(0)
	log.SetOutput(os.Stdout)

	var server string

	flag.StringVar(&server, "server", "udp4://announce.syncthing.net:22026", "Announce server")
	flag.Parse()

	if len(flag.Args()) != 1 || server == "" {
		log.Printf("Usage: %s [-server=\"udp4://announce.syncthing.net:22026\"] <device>", os.Args[0])
		os.Exit(64)
	}

	id, err := protocol.DeviceIDFromString(flag.Args()[0])
	if err != nil {
		log.Println(err)
		os.Exit(1)
	}

	discoverer := discover.NewDiscoverer(protocol.LocalDeviceID, nil)
	discoverer.StartGlobal([]string{server}, 1)
	for _, addr := range discoverer.Lookup(id) {
		log.Println(addr)
	}
}
开发者ID:sgilani,项目名称:Syncthing-iOS,代码行数:26,代码来源:main.go


示例17: main

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	rand.Seed(time.Now().UnixNano())
	flag.Parse()
	if len(flag.Args()) == 0 {
		fmt.Println("usage: im_api config")
		return
	}

	config = read_api_cfg(flag.Args()[0])
	log.Infof("port:%d \n", config.port)

	var err error
	db, err = sql.Open("mysql", config.appdb_datasource)
	if err != nil {
		log.Info("mysql open err:", err)
	} else {
		//use short connection
		db.SetMaxOpenConns(100)
		db.SetMaxIdleConns(0)
	}

	redis_pool = NewRedisPool(config.redis_address, "")

	group_server = NewGroupServer(config.port)
	go group_server.RunPublish()

	RunAPI()
}
开发者ID:karlom,项目名称:im_service,代码行数:29,代码来源:api.go


示例18: main

func main() {
	log.SetFlags(0)
	log.SetPrefix(fmt.Sprintf("%s: ", filepath.Base(os.Args[0])))

	flag.Usage = usage()
	flag.Parse()

	if flag.NArg() > 0 {
		for _, cmd := range commands {
			if cmd.name != flag.Args()[0] {
				continue
			}
			if err := cmd.flag.Parse(flag.Args()[1:]); err != nil {
				cmd.flag.Usage()
			}
			if err := cmd.exec(cmd.flag.Args()...); err != nil {
				if err == errUsage {
					cmd.flag.Usage()
				}
				log.Fatal(err)
			}
			os.Exit(0)
		}
	}
	flag.Usage()
}
开发者ID:sstallion,项目名称:go,代码行数:26,代码来源:main.go


示例19: main

func main() {
	flag.Parse()
	isPublic := !*gistPrivateFlag

	// if nothing was given write message
	if (flag.NFlag() == 0) && (len(flag.Args()) == 0) {
		fmt.Println("No arguments or files given!")
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flag.PrintDefaults()
		os.Exit(2)
	}

	token := Configuration.GetToken()

	if *listGistsFlag != "" {
		username := *listGistsFlag
		url := baseUrl + "users/" + username + "/gists"
		Gist.List(url)
	} else if *deleteGistFlag != "" {
		Gist.Delete(baseUrl, token, *deleteGistFlag)
	} else if *downloadGistFlag != "" {
		Gist.Download(baseUrl, token, *downloadGistFlag)
	} else {
		filesName := flag.Args()
		if len(filesName) == 0 && *updateGistFlag == "" {
			fmt.Println("No files given!")
			os.Exit(2)
		}
		if *updateGistFlag != "" {
			Gist.Update(baseUrl, token, filesName, *updateGistFlag, *gistDescriptionFlag, *openBrowserFlag)
		} else {
			Gist.Post(baseUrl, token, isPublic, filesName, *gistDescriptionFlag, *openBrowserFlag)
		}
	}
}
开发者ID:ramtiga,项目名称:gost,代码行数:35,代码来源:gost.go


示例20: main

func main() {
	flag.Parse()

	if len(flag.Args()) < 1 {
		flag.Usage()
		printUsage()
	}
	target := flag.Args()[0]
	switch target {
	case "version":
		version()
		return
	case "serve":
		target = flag.Args()[1]
		server(target)
	case "query":
		target = flag.Args()[1]
		query(target)
	case "hash":
		target = flag.Args()[1]
		hash(target)
	default:
		execute(target)
	}
}
开发者ID:ftrvxmtrx,项目名称:build,代码行数:25,代码来源:main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang flag.Bool函数代码示例发布时间:2022-05-24
下一篇:
Golang flag.Arg函数代码示例发布时间: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