Golang flag.PrintDefaults类(方法)实例源码

下面列出了Golang flag.PrintDefaults 类(方法)源码代码实例,从而了解它的用法。

作者:runco    项目:goss   
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)

}

作者:hit    项目:noise.ol   
func main() {
	detector := flag.Bool("detector", false, "start detector")
	// webapp := flag.Bool("webapp", false, "start webapp")
	// alerter := flag.Bool("alerter", false, "start alerter")
	fileName := flag.String("config", "", "config path")
	version := flag.Bool("version", false, "show version")
	flag.Parse()
	if *version {
		fmt.Fprintln(os.Stderr, VERSION)
		os.Exit(1)
	}
	if flag.NFlag() != 2 {
		flag.PrintDefaults()
		os.Exit(1)
	}
	cfg, err := config.NewWithJsonFile(*fileName)
	if err != nil {
		log.Fatalf("failed to read %s: %v", *fileName, err)
	}
	switch {
	case *detector:
		StartDetector(cfg.Detector)
	default:
		flag.PrintDefaults()
		os.Exit(1)
	}
}

作者:gabesullic    项目:reape   
func init() {
	flag.StringVar(&address, "address", "localhost:28015", "The address to connect to a RethinkDB instance.")
	flag.StringVar(&db, "database", "", "The RethinkDB database to use.")
	flag.StringVar(&table, "table", "", "The RethinkDB database table to use.")
	flag.Parse()

	if len(db) == 0 {
		fmt.Println("You must pass the name of a database to use.\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if len(table) == 0 {
		fmt.Println("You must pass the name of database table to use.\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	//session, err := r.Connect(r.ConnectOpts{
	//	Address:  address,
	//	Database: db,
	//	MaxIdle:  10,
	//	MaxOpen:  10,
	//})
	//if err != nil {
	//	log.Fatalln(err.Error())
	//}
}

作者:kitec    项目:toxs   
func main() {
	flag.Parse()
	if len(config_file) > 0 {
		config = NewTunnelConfig(config_file)
		info.Println(config)
	}

	argv := flag.Args()
	argc := len(argv)

	mode := ""
	if argc > 0 {
		mode = argv[argc-1]
	}

	go NewStatServer().serve()
	appevt.Trigger("appmode", mode)

	switch mode {
	case "client":
		if config == nil {
			flag.PrintDefaults()
			os.Exit(-1)
		}
		tc := NewTunnelc()
		tc.serve()
	case "server":
		td := NewTunneld()
		td.serve()
	default:
		log.Println("Invalid mode")
		flag.PrintDefaults()
	}

}

作者:cj12    项目:rove   
func init() {
	flag.StringVar(&sourceURL, "u", "", "the url you wish to download from")
	flag.StringVar(&remoteFile, "r", "", "the remote filename to download")
	flag.StringVar(&localFile, "o", "", "the output filename")
	flag.IntVar(&timeout, "t", 5, "timeout, in seconds")
	flag.BoolVar(&verbose, "v", false, "verbose")
	flag.BoolVar(&showFiles, "l", false, "list files in zip")
	flag.Uint64Var(&limitBytes, "b", 0, "limit filesize downloaded (in bytes)")

	flag.Parse()

	if sourceURL == "" {
		fmt.Println("You must specify a URL")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if !showFiles {
		if remoteFile == "" {
			fmt.Println("You must specify a remote filename")
			flag.PrintDefaults()
			os.Exit(1)
		}

		if localFile == "" {
			_, localFile = filepath.Split(remoteFile)
		}
	}
}

作者:Svenit    项目:google-go-cpu-usag   
/**
* Our main entry point.
* @return{struct} Our config structure populated with configuration info.
 */
func Main() Config {

	config := Config{}
	flag.IntVar(&config.Num_messages, "num-messages", 1,
		"How many messages to send?")
	flag.IntVar(&config.Message_size, "message-size", 1,
		"How many bytes in each message?")
	flag.IntVar(&config.Num_cores, "num-cores", 1,
		"How many cores to use? (Max:"+strconv.Itoa(runtime.NumCPU())+")")
	flag.IntVar(&config.Buffer_size, "buffer-size", 0,
		"Buffer size for our channel?")
	flag.IntVar(&config.Num_goroutines, "num-goroutines", 1,
		"How many goroutines to run?")
	flag.IntVar(&config.Num_goroutine_work, "num-goroutine-work", 1,
		"How much work to do in each goroutine?")

	var h = flag.Bool("h", false, "Print this help")
	var help = flag.Bool("help", false, "Print this help")

	flag.Parse()

	if *h || *help {
		flag.PrintDefaults()
		panic("Bailing out due to asking for help")

	} else if config.Num_goroutine_work < 1 {
		flag.PrintDefaults()
		panic("Goroutine work must be >= 1")

	}

	return (config)

} // End of Main()

作者:OpenWhiteBo    项目:AE   
func main() {
	flag.Parse()
	block, err := hex.DecodeString(*hexBlock)
	if err != nil {
		log.Println(err)
		flag.PrintDefaults()
		return
	} else if len(block) != 16 {
		log.Println("Block must be 128 bits.")
		flag.PrintDefaults()
		return
	}

	// Read construction from disk and parse it into something usable.
	data, err := ioutil.ReadFile("./constr.txt")
	if err != nil {
		log.Fatal(err)
	}
	constr, err := full.Parse(data)
	if err != nil {
		log.Fatal(err)
	}

	// Encrypt block in-place, and print as hex.
	constr.Encrypt(block, block)
	fmt.Printf("%x\n", block)
}

作者:goldenber    项目:sample   
func main() {
	flag.Float64Var(&samplingProbability, "p", 0.0, "Sample lines at probability p in [0, 1].")
	flag.UintVar(&reservoirSize, "r", 0, "Sample exactly k lines.")
	flag.StringVar(&splitStr, "s", "", "Split the input into n random subsets. Delimit weights with commas, e.g. 8,1,1. Weights will be normalized to sum to 1.")
	flag.StringVar(&outputFilename, "o", "", "Output file(s). If not specified, write to stdout. Required and used as a basename for splitting. The basename will be appended with _1, _2, etc.")
	flag.Parse()

	rand.Seed(time.Now().UnixNano())

	if reservoirSize > 0 && samplingProbability > 0.0 {
		fmt.Println("You can specify either -p or -r, but not both.")
		flag.PrintDefaults()
		return
	}

	input := inputReader(flag.Args())

	if splitStr != "" {
		if outputFilename == "" {
			fmt.Println("To split input, you must specify an output base filename with -o.")
			flag.PrintDefaults()
			return
		}
		Split(input)
	} else if samplingProbability > 0.0 {
		sampleAtRate(input, samplingProbability, os.Stdout)
	} else if reservoirSize > 0 {
		lines := reservoirSample(input, reservoirSize)

		for _, line := range lines {
			fmt.Print(line)
		}
	}
}

作者:kenp    项目:presentl   
func main() {
	flag.StringVar(&presently.Dir, "d", "", "Directory of the repository")
	flag.StringVar(&presently.DeployDir, "o", "", "Directory of the deployment")
	flag.StringVar(&presently.Port, "p", "", "Port to listen")
	flag.Parse()
	args := flag.Args()

	if presently.Dir == "" {
		if len(args) == 0 {
			fmt.Println("You need to specify -d")
			flag.PrintDefaults()
			os.Exit(0)
		} else {
			presently.Dir = args[0]
		}
	}

	if presently.DeployDir == "" {
		fmt.Println("You need to specify -o")
		flag.PrintDefaults()
		os.Exit(0)
	}

	presently.Deploy()
}

作者:orebokec    项目:fatbi   
func main() {
	// redefine the flags function
	flag.Usage = func() {
		// print defaults of fatbin only if it's named fatbin
		if filepath.Base(os.Args[0]) == "fatbin" {
			flag.PrintDefaults()
			return
		}
	}

	// read the flags

	err := parseFlags()
	if err != nil {
		fmt.Println(err)
		flag.PrintDefaults()
		return
	}

	// compress mode
	if len(flags.Directory) > 0 && len(flags.Executable) > 0 {
		build()
		return
	}

	run()
}

作者:mysl    项目:flyne   
func main() {
	flag.Parse()
	if *help {
		fmt.Println(useage)
		flag.PrintDefaults()
		return
	}

	if *dbname == "" {
		fmt.Println(useage)
		flag.PrintDefaults()
		return
	}

	if *source == "" {
		fmt.Println(useage)
		flag.PrintDefaults()
		return
	}

	if *path == "" {
		fmt.Println(useage)
		flag.PrintDefaults()
		return
	}

	sync := db.CreateSyncDB(*dbname, *source)
	sync.SyncDB(*path, *drop, *role)

}

作者:GoogleCloudPlatfor    项目:golang-sample   
func main() {
	flag.Parse()

	if *apiKey == "" || *host == "" {
		flag.PrintDefaults()
		os.Exit(1)
	}
	if *serviceAccount == "" && *echo == "" {
		fmt.Fprint(os.Stderr, "Provide one of -echo or -service-account.")
		flag.PrintDefaults()
		os.Exit(1)
	}
	if *serviceAccount != "" && *echo != "" {
		fmt.Fprint(os.Stderr, "Provide only one of -echo or -service-account.")
		flag.PrintDefaults()
		os.Exit(1)
	}

	var resp *http.Response
	var err error
	if *echo != "" {
		resp, err = doEcho()
	} else if *serviceAccount != "" {
		resp, err = doJWT()
	}
	if err != nil {
		log.Fatal(err)
	}
	b, err := httputil.DumpResponse(resp, true)
	if err != nil {
		log.Fatal(err)
	}
	os.Stdout.Write(b)
}

作者:kapitano    项目:logtai   
func main() {
	flag.Parse()
	if !flag.Parsed() {
		fmt.Fprintf(os.Stderr, "Invalid command line!\n")
		flag.PrintDefaults()
		return
	}

	if len(flag.Args()) < 1 {
		fmt.Fprintf(os.Stderr, "No file is specified\n")
		flag.PrintDefaults()
		return
	}

	filename := flag.Arg(0)

	file, err := NewLogFile(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "NewLogFile() failed! %s\n", err)
		panic(err)
	}
	defer file.Close()

	err = file.Monitor(*linesToPrint)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Monitor() failed! %s\n", err)
		panic(err)
	}

	shutdown := make(chan bool)
	<-shutdown
}

作者:jonse    项目:tiedo   
func main() {
	var defaultMaxprocs int
	var err error
	if defaultMaxprocs, err = strconv.Atoi(os.Getenv("GOMAXPROCS")); err != nil {
		defaultMaxprocs = runtime.NumCPU() * 2
	}
	var mode, dir string
	var port, maxprocs int
	flag.StringVar(&mode, "mode", "", "[v1|v2|v3|bench|durable-bench|example]")
	flag.StringVar(&dir, "dir", "", "database directory")
	flag.IntVar(&port, "port", 0, "listening port number")
	flag.IntVar(&maxprocs, "gomaxprocs", defaultMaxprocs, "GOMAXPROCS")
	flag.Parse()

	if mode == "" {
		flag.PrintDefaults()
		return
	}

	runtime.GOMAXPROCS(maxprocs)
	log.Printf("GOMAXPROCS is set to %d", maxprocs)

	if maxprocs < runtime.NumCPU() {
		log.Printf("GOMAXPROCS (%d) is less than number of CPUs (%d), this may affect performance. You can change it via environment variable GOMAXPROCS or by passing CLI parameter -gomaxprocs", maxprocs, runtime.NumCPU())
	}

	switch mode {
	case "v1":
		fallthrough
	case "v2":
		fallthrough
	case "v3":
		if dir == "" {
			log.Fatal("Please specify database directory, for example -dir=/tmp/db")
		}
		if port == 0 {
			log.Fatal("Please specify port number, for example -port=8080")
		}
		db, err := db.OpenDB(dir)
		if err != nil {
			log.Fatal(err)
		}
		if mode == "v1" {
			v1.Start(db, port)
		} else if mode == "v2" {
			v2.Start(db, port)
		} else if mode == "v3" {
			v3.Start(db, port)
		}
	case "bench":
		benchmark()
	case "durable-bench":
		durableBenchmark()
	case "example":
		embeddedExample()
	default:
		flag.PrintDefaults()
		return
	}
}

作者:roachm    项目:pingpon   
func main() {
	aspong := flag.Bool("asPong", false, "Starts Pong service")
	asping := flag.Bool("asPing", false, "Starts Ping service")
	port := flag.Int("port", 8080, "Sets the port")
	ponghost := flag.String("pongHost", "localhost", "Host (valid DNS name or IP) of the pong service")
	pongport := flag.Int("pongPort", 8080, "Port of the pong service")
	flag.Parse()

	if *aspong && *asping {
		fmt.Println("You can only start ping or pong service, not both with the same command.")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if *aspong {
		pong.Start(*port)
		os.Exit(0)
	}

	if *asping {
		ping.Start(*port, *ponghost, *pongport)
		os.Exit(0)
	}

	flag.PrintDefaults()
}

作者:agaffne    项目:livestatus-htt   
func Main() {
	// Parse commandline
	opts := &http.Options{}
	var fork bool
	flag.BoolVar(&fork, "fork", false, "fork into the background")
	flag.StringVar(&opts.ListenAddr, "listenaddr", "0.0.0.0", "address of interface to listen on")
	flag.IntVar(&opts.ListenPort, "listenport", 6558, "port to listen on")
	flag.BoolVar(&opts.Xinetd, "xinetd", false, "service is running under xinetd")
	flag.StringVar(&opts.LivestatusSocket, "livestatus-socket", "", "path to Livestatus UNIX socket")
	flag.StringVar(&opts.LivestatusAddress, "livestatus-address", "", "address (host:port) of livestatus TCP endpoint")
	flag.Parse()

	if opts.Xinetd && fork {
		fmt.Println("You cannot specify both 'fork' and 'xinetd' options at the same time\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	if opts.LivestatusSocket == "" && opts.LivestatusAddress == "" {
		fmt.Println("You must specify the livestatus endpoint information\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	err := http.Start(opts)
	if err != nil {
		fmt.Printf("Error: %s\n\n", err)
		os.Exit(1)
	}
}

作者:owlfis    项目:forestbus-serve   
func main() {
	// Initialise our configuration from flags

	var nodeName = flag.String("name", REQUIRED, "Node network name and port, e.g. localhost:3000")
	var gobName = flag.String("gob", "", "Alternative gob network name and port for clients, allowing clients to connect over a different physical interface to nodes.")
	var httpName = flag.String("http", "", "Network name and port for the http ExpVar to listen on.")
	var cborName = flag.String("cbor", "", "Network name and port for the CBOR RPC interface to listen on.")
	var nodePath = flag.String("path", REQUIRED, "Node root path for configuration and log files")
	var clusterID = flag.String("id", "", "Cluster ID that this node is part of")

	flag.Parse()

	if flag.Lookup("help") != nil || flag.Lookup("h") != nil {
		flag.PrintDefaults()
		return
	}

	if *nodeName == REQUIRED {
		log.Printf("name missing.\n")
		flag.PrintDefaults()
		return
	}

	if *nodePath == REQUIRED {
		log.Printf("path missing.\n")
		flag.PrintDefaults()
		return
	}

	// Create our server
	serverNode, err := server.NewServerNode(*nodeName, *gobName, *httpName, *cborName, *nodePath, *clusterID)

	if err != nil {
		log.Fatalf("Unable to start server due to errors.\n")
	}

	expvar.Publish("node", expvar.Func(serverNode.ExpVar))

	//dataLog := &memlog.MemoryLog{}

	// Start a listener to handle incoming requests from other peers
	err = serverNode.ListenConnections()
	if err != nil {
		log.Fatalf("Error starting listener: %v\n", err)
	}

	// Setup signal handling to catch interrupts.
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc,
		os.Interrupt,
		os.Kill)
	go func() {
		<-sigc
		serverNode.RequestShutdown("Request to terminate process detected.")
	}()

	serverNode.WaitForShutdown()

}

作者:horg    项目:song_tracker   
// main is the entry point of the program.
func main() {
	log.SetFlags(log.Ldate | log.Ltime)

	// command line arguments.
	configPath := flag.String("config-file", "",
		"Path to a configuration file.")
	logPath := flag.String("log-file", "",
		"Path to a log file.")
	flag.Parse()
	// config file is required.
	if len(*configPath) == 0 {
		log.Print("You must specify a configuration file.")
		flag.PrintDefaults()
		os.Exit(1)
	}
	if len(*logPath) == 0 {
		log.Print("You must specify a log file.")
		flag.PrintDefaults()
		os.Exit(1)
	}

	// open log file.
	// don't use os.Create() because that truncates.
	logFh, err := os.OpenFile(*logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
	if err != nil {
		log.Printf("Failed to open log file: %s: %s", *logPath, err.Error())
		os.Exit(1)
	}
	log.SetOutput(logFh)

	// load up our settings.
	var settings Config
	err = config.GetConfig(*configPath, &settings)
	if err != nil {
		log.Printf("Failed to retrieve config: %s", err.Error())
		os.Exit(1)
	}

	// start listening.
	var listenHostPort = fmt.Sprintf("%s:%d", settings.ListenHost,
		settings.ListenPort)
	listener, err := net.Listen("tcp", listenHostPort)
	if err != nil {
		log.Print("Failed to open port: " + err.Error())
		os.Exit(1)
	}

	httpHandler := HttpHandler{settings: &settings}

	// XXX: this will serve requests forever - should we have a signal
	//   or a method to cause this to gracefully stop?
	log.Print("Starting to serve requests.")
	err = fcgi.Serve(listener, httpHandler)
	if err != nil {
		log.Print("Failed to start serving HTTP: " + err.Error())
		os.Exit(1)
	}
}

作者:mandolyt    项目:sudok   
func main() {
	// parse command line
	flag.Parse()

	// help?
	if *help {
		flag.PrintDefaults()
		os.Exit(0)
	}

	p := sudoku.NewPuzzle()
	if flag.NFlag() == 0 {
		// load from stdin
		if err := p.Load(); err != nil {
			log.Fatalf("Error processing puzzle:%v", err)
		}
	} else {
		// load from input file
		// must have an input argument
		if *input == "" {
			flag.PrintDefaults()
			os.Exit(0)
		}
		fpuz, err := ioutil.ReadFile(*input)
		if err != nil {
			log.Fatalf("Cannot read %v, err=%v", *input, err)
		}
		if err = p.Fload(fpuz); err != nil {
			log.Fatalf("Error processing puzzle:%v", err)
		}
	}
	var w *os.File
	w = os.Stdout
	if *otput != "" {
		var err error
		if w, err = os.Create(*otput); err != nil {
			log.Fatalf("Error opening output %v was:%v\n",
				*otput, err)
		}
	}

	// now that we have the puzzle constructed,
	// set the pencil marks and set any cells to those with
	// only one pencil mark possible
	p.SetPencilMarks()
	p.SetSingleMarks()

	sudoku.Solve(p)
	solutions := sudoku.GetSolutions()
	//number_solutions := len(solutions)
	//fmt.Printf("Number of solutions is:%v\n",number_solutions)
	for _, s := range solutions {
		fmt.Fprintf(w, "%v", s)
	}
	if *rate {
		fmt.Fprintf(os.Stderr, "Rating:%v\n", sudoku.Counter)
	}
}

作者:stevendann    项目:chef-loa   
func main() {
	fConfig := flag.String("config", "", "Configuration file to load")
	fHelp := flag.Bool("help", false, "Print this help")
	fNodes := flag.String("nodes", "", "Number of nodes making chef-client runs")
	fRuns := flag.String("runs", "", "Number of chef-client runs each node should make, 0 value will make infinite runs")
	fSampleConfig := flag.Bool("sample-config", false, "Print out full sample configuration")
	fVersion := flag.Bool("version", false, "Print chef-load version")
	flag.Parse()

	if *fHelp {
		fmt.Println("Usage of chef-load:")
		flag.PrintDefaults()
		os.Exit(0)
	}

	if *fVersion {
		fmt.Println("chef-load", AppVersion)
		os.Exit(0)
	}

	if *fSampleConfig {
		printSampleConfig()
		os.Exit(0)
	}

	var (
		config *chefLoadConfig
		err    error
	)

	if *fConfig != "" {
		config, err = loadConfig(*fConfig)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		fmt.Println("Usage of chef-load:")
		flag.PrintDefaults()
		return
	}

	if *fNodes != "" {
		config.Nodes, _ = strconv.Atoi(*fNodes)
	}

	if *fRuns != "" {
		config.Runs, _ = strconv.Atoi(*fRuns)
	}

	numNodes := config.Nodes
	for i := 0; i < numNodes; i++ {
		nodeName := config.NodeNamePrefix + "-" + strconv.Itoa(i)
		go startNode(nodeName, *config)
	}
	for i := 0; i < numNodes; i++ {
		<-quit // Wait to be told to exit.
	}
}


问题


面经


文章

微信
公众号

扫码关注公众号