Golang Args示例

说明

golang args示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: flag

示例#1
文件: clean.go 项目: gouvinb/goclean

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)
		}
	}
}

示例#2
文件: redis-monitor.go 项目: mehulsbhatt/gollector-monitors

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)
	}
}

示例#3
文件: statsrelay.go 项目: denen99/statsrelay

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")
}

示例#4
文件: main.go 项目: dazer-chen/gopacket

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)
}

示例#5
文件: sum.go 项目: postfix/rshasum

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)
			}
		}
	}
}

示例#6
文件: doozer.go 项目: musicglue/doozer

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)
}

示例#7
文件: main.go 项目: jcantrill/geard

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)
}

示例#8
文件: chmod.go 项目: u-root/u-root

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)
	}

}

示例#9
文件: loadfile.go 项目: jchris/indexing

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)
	}
}

示例#10
文件: main.go 项目: andrebq/exp

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:]...)
		}
	}
}

示例#11
文件: main.go 项目: CodeMonk/GoSquareToShopify

// 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
}

示例#12
文件: main.go 项目: litixsoft/lxb

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()
	}
}

示例#13
文件: main.go 项目: scalp42/s3proxy

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)
}

示例#14
文件: main.go 项目: hyg/go.sample

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)
	}
}

示例#15
文件: goprint.go 项目: maddyonline/gddo

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)
}

示例#16
文件: main.go 项目: sgilani/Syncthing-iOS

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)
	}
}

示例#17
文件: api.go 项目: karlom/im_service

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()
}

示例#18
文件: main.go 项目: sstallion/go

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()
}

示例#19
文件: gost.go 项目: ramtiga/gost

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)
		}
	}
}

示例#20
文件: main.go 项目: ftrvxmtrx/build

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)
	}
}

示例#21
文件: mksyscall_dll.go 项目: Archs/mksyscall_dll

func main() {
	flag.Usage = usage
	pkgName := flag.String("p", "", "package name, if not speficied using the input file name instead")
	outFile := flag.String("o", "", "output file, if not speficied using stdout instead")
	flag.Parse()
	if len(flag.Args()) < 1 {
		fmt.Fprintf(os.Stderr, "no files to parse provided\n")
		usage()
	}
	// parse files
	src, err := ParseFiles(flag.Args())
	if err != nil {
		log.Fatal(err)
	}
	if *pkgName != "" {
		src.PkgName = *pkgName
	}
	// output file
	var out io.Writer
	if *outFile != "" {
		out, err = os.OpenFile(*outFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		out = os.Stdout
	}
	if err := src.Generate(out); err != nil {
		log.Fatal(err)
	}
}

示例#22
文件: ltr.go 项目: stanim/svgof

func main() {
	x := 0.0
	y := 0.0
	nd := float64(len(flag.Args()))
	for i, dir := range flag.Args() {
		filelist := imagefiles(dir)
		if len(filelist) != ni || filelist == nil {
			fmt.Fprintf(os.Stderr, "in the %s directory, need %.4f images, read %.4f\n", dir, ni, len(filelist))
			continue
		}
		switch {

		case opacity:
			if i == 0 {
				canvas.Start(width*nd, height*nd)
				dotitle(dir)
			}
			ltop(x, y, width, height, filelist)
			y += height

		case poster:
			if i == 0 {
				canvas.Start(width, ((height*(ni-1)/4)+height)*nd)
				dotitle(dir)
			}
			ltposter(x, y, width/2, height/2, filelist)
			y += (height * 3.0) + (height / 2.0)

		case col:
			if i == 0 {
				canvas.Start(width*nd, height*ni)
				dotitle(dir)
			}
			ltcol(x, y, width, height, filelist)
			x += width

		case row:
			if i == 0 {
				canvas.Start(width*ni, height*nd)
				dotitle(dir)
			}
			ltrow(x, y, width, height, filelist)
			y += height

		case offset:
			n := ni - 1.0
			pw := width * 2.0
			ph := nd * (height * (n))
			if i == 0 {
				canvas.Start(pw, ph)
				canvas.Rect(0, 0, pw, ph, "fill:white")
				dotitle(dir)
			}
			ltoffset(x, y, width, height, filelist)
			y += n * height

		}
	}
	canvas.End()
}

示例#23
文件: main.go 项目: jravasi/go-fuse

func main() {
	debug := flag.Bool("debug", false, "debug on")
	threaded := flag.Bool("threaded", true, "debug on")
	delcache_ttl := flag.Float64("deletion_cache_ttl", 5.0, "Deletion cache TTL in seconds.")
	branchcache_ttl := flag.Float64("branchcache_ttl", 5.0, "Branch cache TTL in seconds.")
	deldirname := flag.String(
		"deletion_dirname", "GOUNIONFS_DELETIONS", "Directory name to use for deletions.")
	flag.Parse()

	if len(flag.Args()) < 2 {
		fmt.Println("Usage:\n  main MOUNTPOINT RW-DIRECTORY RO-DIRECTORY ...")
		os.Exit(2)
	}

	ufsOptions := unionfs.UnionFsOptions{
		DeletionCacheTTLSecs: *delcache_ttl,
		BranchCacheTTLSecs:   *branchcache_ttl,
		DeletionDirName:      *deldirname,
	}

	ufs, err := unionfs.NewUnionFsFromRoots(flag.Args()[1:], &ufsOptions)
	if err != nil {
		log.Fatal("Cannot create UnionFs", err)
		os.Exit(1)
	}
	mountState, _, err := fuse.MountFileSystem(flag.Arg(0), ufs, nil)
	if err != nil {
		log.Fatal("Mount fail:", err)
	}

	mountState.Debug = *debug
	mountState.Loop(*threaded)
}

示例#24
文件: main.go 项目: mehulsbhatt/sandbox-1

func main() {
	flag.BoolVar(&CmdlineOptions.Verbose, "v", false, "Verbose")
	flag.BoolVar(&CmdlineOptions.WaitForEvent, "w", false, "For commands that return an event_id, wait for the event to complete.")
	InitRoutingTable()
	flag.Parse()
	route := FindMatchingRoute(flag.Args())
	if CmdlineOptions.Verbose {
		fmt.Fprintf(os.Stderr, "Args: %s\n", flag.Args())
	}
	if CmdlineOptions.Verbose {
		fmt.Fprintf(os.Stderr, "Route: %s\n", route)
	}

	if route == nil {
		fmt.Fprintf(os.Stderr, "Error: unrecognized command: %s\n", flag.Args())
		ShowGeneralHelp(route)
		os.Exit(1)
	}

	if !InitConfig() {
		fmt.Fprintf(os.Stderr, "Invalid or Missing configuration file.\n")
		os.Exit(1)
	}
	if CmdlineOptions.Verbose {
		fmt.Fprintf(os.Stderr, "Config: %s\n", Config)
	}

	if route != nil {
		if CmdlineOptions.Verbose {
			fmt.Fprintf(os.Stderr, "Calling route: %s\n", route)
		}
		route.Handler(route)
	}
}

示例#25
文件: seq.go 项目: mstipetic/go_coreutils

func main() {
	var separator string
	flag.StringVar(&separator, "s", "\n", "Element separator")
	flag.Parse()

	var first, last int
	var err error

	if len(flag.Args()) == 1 {
		first = 1
		if last, err = strconv.Atoi(flag.Args()[0]); err != nil {
			fmt.Println(err)
			return
		}
	} else if len(flag.Args()) == 2 {
		if first, err = strconv.Atoi(flag.Args()[0]); err != nil {
			fmt.Println(err)
			return
		}
		if last, err = strconv.Atoi(flag.Args()[1]); err != nil {
			fmt.Println(err)
			return
		}
	}

	for i := first; i <= last; i++ {
		fmt.Printf("%d%s", i, separator)
	}
}

示例#26
文件: tumblrgrid.go 项目: stanim/svgof

func main() {

	np := len(flag.Args())
	if np == 0 {
		np = 1.0
	}

	thalf := thumbwidth / 2.0
	x := thalf
	y := 50.0
	nrows := piclimit / ncols
	colincr := (ncols * thumbwidth) + (ncols * gutter) + thalf
	width := (colincr * float64(np)) + thalf
	height := (thumbwidth * nrows) + (nrows * gutter) + y + thalf
	gstyle := "font-family:Calibri,sans-serif;font-size:18px"

	canvas := svg.New(os.Stdout)
	canvas.Start(width, height)
	canvas.Rect(0, 0, width, height, "fill:rgb(43,62,87)") // tumblr blue
	canvas.Gstyle(gstyle)
	if len(flag.Args()) == 0 {
		grid(canvas, "", x, y, ncols, gutter)
	} else {
		for _, f := range flag.Args() {
			grid(canvas, f, x, y, ncols, gutter)
			x += colincr
		}
	}
	canvas.Gend()
	canvas.End()
}

示例#27
文件: gobig.go 项目: visualmotive/gobig

func main() {
	templates := flag.String("template", "template", "Template directory")
	flag.Parse()
	if len(flag.Args()) != 2 {
		fmt.Println("Usage: gobig [--title=site-title] [--template=dir] src dest")
		return
	}

	sPath := flag.Args()[0]
	dPath := flag.Args()[1]

	s := Source{sPath}

	renderer := Renderer{*templates, dPath}

	site := s.Site()
	posts := s.All()
	log.Printf("%d %s found", len(posts), pluralize("post", len(posts)))

	// link all posts to each other
	linkPosts(posts)

	// convert markdown to html when appropriate
	toHTML(posts)

	err := renderer.RenderAll(site, posts)
	if err != nil {
		log.Panicf(err.Error())
	}
	log.Printf("Done.")
}

示例#28
文件: mksyscall_windows.go 项目: supasate/docker

func main() {
	flag.Usage = usage
	flag.Parse()
	if len(flag.Args()) <= 0 {
		fmt.Fprintf(os.Stderr, "no files to parse provided\n")
		usage()
	}

	src, err := ParseFiles(flag.Args())
	if err != nil {
		log.Fatal(err)
	}

	var buf bytes.Buffer
	if err := src.Generate(&buf); err != nil {
		log.Fatal(err)
	}

	data, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	if *filename == "" {
		_, err = os.Stdout.Write(data)
	} else {
		err = ioutil.WriteFile(*filename, data, 0644)
	}
	if err != nil {
		log.Fatal(err)
	}
}

示例#29
文件: service.go 项目: cloudconductor/metronome

func (service *Service) Manage() (string, error) {
	usage := "Usage: metronome install | remove | start | stop | status | agent\n"

	if flag.NArg() > 0 {
		switch flag.Args()[0] {
		case "install":
			return service.Install()
		case "remove":
			return service.Remove()
		case "start":
			return service.Start()
		case "stop":
			return service.Stop()
		case "status":
			return service.Status()
		case "agent":
			return agent()
		case "push":
			return scheduler.Push()
		case "dispatch":
			return dispatch(flag.Args()[1])
		case "version":
			log.SetFormatter(&util.SimpleFormatter{})
			return fmt.Sprintf("metronome %s\n", Version), nil
		default:
			log.SetFormatter(&util.SimpleFormatter{})
			return usage, nil
		}
	}
	return agent()
}

示例#30
文件: dhproxy.go 项目: drbig/golang

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s [options] PORT\n", os.Args[0])
		flag.PrintDefaults()
	}

	var host string
	flag.StringVar(&host, "h", "127.0.0.1", "HTTP server bind HOST")
	flag.Parse()
	if len(flag.Args()) < 1 {
		die("You have to specify a port!", 2)
	}
	port, err := strconv.Atoi(flag.Args()[0])
	if err != nil || port <= 0 {
		die("Port has to be a positive integer!", 2)
	}

	proxy := goproxy.NewProxyHttpServer()
	proxy.OnRequest().DoFunc(
		func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
			fmt.Println(req.RequestURI)
			return req, nil
		})
	log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", host, port), proxy))
}

展开阅读全文