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

Golang flag.Parsed函数代码示例

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

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



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

示例1: Serve

// Serve starts Goji using reasonable defaults.
func Serve() {
	if !flag.Parsed() {
		flag.Parse()
	}

	log.SetFlags(log.Flags() | log.Lmicroseconds)

	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", DefaultMux)

	listener := bind.Default()
	log.Println("Starting Goji on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()

	err := graceful.Serve(listener, http.DefaultServeMux)

	if err != nil {
		log.Fatal(err)
	}

	graceful.Wait()
}
开发者ID:brandonparsons,项目名称:simulation.retirementplan.io,代码行数:26,代码来源:goji.go


示例2: Initialize

// Initialize constructs appropriate Credential structure based on
// provided data, which includes, in the following precedence (later
// superseding earlier):
// * In case of username/password auth:
//   1. As keys UsernameKey and PasswordKey in ~/.romana.yaml file
//   2. As environment variables whose names are UsernameKey and PasswordKey values
//   3. As --username and --password command-line flags.
//      If --username flag is specified but --password flag is omitted,
//      the user will be prompted for the password.
// Notes:
// 1. The first two precedence steps (~/.romana.yaml and environment variables)
//    are taken care by the config module (github.com/spf13/viper)
// 2. If flag.Parsed() is false at the time of this call, the command-line values are
//    ignored.
//
func (c *Credential) Initialize() error {
	username := config.GetString(UsernameKey)
	password := config.GetString(PasswordKey)
	if c.assumeFlagParsed || flag.Parsed() {
		if c.userFlag != "" {
			username = c.userFlag
			if c.passFlag == "" {
				// Ask for password
				var err error
				password, err = GetPasswd()
				if err != nil {
					return err
				}
			} else {
				password = c.passFlag
			}
		}
	}
	if username != "" {
		//
		c.Username = username
		c.Password = password
		c.Type = CredentialUsernamePassword
	} else {
		// For now, credential is None if not specified
		c.Type = CredentialNone
	}
	return nil
}
开发者ID:romana,项目名称:core,代码行数:44,代码来源:auth.go


示例3: loadConfig

func loadConfig() (*Config, error) {

	var configFlag string
	var versionFlag bool

	if !flag.Parsed() {
		flag.StringVar(&configFlag, "config", "",
			"JSON config or file:// path to JSON config file.")
		flag.BoolVar(&versionFlag, "version", false, "Show version identifier and quit.")
		flag.Parse()
	} else {
		// allows for safe configuration reload
		configFlag = flag.Lookup("config").Value.String()
	}
	if versionFlag {
		fmt.Printf("Version: %s\nGitHash: %s\n", Version, GitHash)
		os.Exit(0)
	}
	if configFlag == "" {
		configFlag = os.Getenv("CONTAINERBUDDY")
	}

	config, err := parseConfig(configFlag)
	if err != nil {
		return nil, err
	}
	return initializeConfig(config)
}
开发者ID:zofuthan,项目名称:containerbuddy,代码行数:28,代码来源:config.go


示例4: createNewFiles

// createNewFiles creates all the log files for severity from sev down to infoLog.
// l.mu is held.
func (l *loggingT) createNewFiles() error {
	l.mu.Lock()
	defer l.mu.Unlock()

	if !flag.Parsed() {
		return fmt.Errorf("ERROR: logging before flag.Parse: ")
	} else if l.toStderr {
		return nil
	}

	now := time.Now()
	// Files are created in decreasing severity order, so as soon as we find one
	// has already been created, we can stop.
	for s := fatalLog; s >= infoLog; s-- {
		if l.file[s] == nil {
			continue
		}

		if sb, ok := l.file[s].(*syncBuffer); ok {
			if err := sb.rotateFile(now); err != nil {
				return err
			}
		}
	}

	return nil
}
开发者ID:chinawebeye,项目名称:glog,代码行数:29,代码来源:glog.go


示例5: HandlerFunc

// HandlerFunc returns the http handler func, which renders the
// template with the data.
func (p page) HandlerFunc() http.HandlerFunc {
	fn := func(w http.ResponseWriter, r *http.Request) {
		data, err := p.getTemplateData(w, r)
		if err != nil {
			glog.Errorf("error getting template data: %v\n", err)
			serveISE(w)
			return
		}
		err = p.tmpl.ExecuteTemplate(w, baseTemplate, data)
		if err != nil {
			glog.Errorf("error rendering template: %v\n", err)
			serveISE(w)
			return
		}
	}

	if !flag.Parsed() {
		flag.Parse()
	}
	if *authDisabled {
		glog.Infof("-disabled_auth is set, not checking credentials\n")
	} else {
		fn = googleauth.RequireLogin(fn)
	}
	return fn
}
开发者ID:mehulsbhatt,项目名称:dashboard-3,代码行数:28,代码来源:router.go


示例6: Run

// Run runs the tests. It returns an exit code to pass to os.Exit.
func (m *M) Run() int {
	// TestMain may have already called flag.Parse.
	if !flag.Parsed() {
		flag.Parse()
	}

	parseCpuList()

	m.before()
	startAlarm()
	haveExamples = len(m.examples) > 0
	testRan, testOk := runTests(m.deps.MatchString, m.tests)
	exampleRan, exampleOk := runExamples(m.deps.MatchString, m.examples)
	if !testRan && !exampleRan && *matchBenchmarks == "" {
		fmt.Fprintln(os.Stderr, "testing: warning: no tests to run")
	}
	if !testOk || !exampleOk || !runBenchmarks(m.deps.MatchString, m.benchmarks) {
		fmt.Println("FAIL")
		m.after()
		return 1
	}

	fmt.Println("PASS")
	m.after()
	return 0
}
开发者ID:thinkingo,项目名称:go,代码行数:27,代码来源:testing.go


示例7: main

func main() {
	flag.Parse()

	if !flag.Parsed() || filename == "" || socket == "" {
		flag.Usage()
		os.Exit(1)
	}

	f, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	l, err := net.Listen("unix", socket)
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	var a net.Conn
	a, err = l.Accept()
	if err != nil {
		log.Fatal(err)
	}
	defer a.Close()

	listenConn := a.(*net.UnixConn)
	if err = fd.Put(listenConn, f); err != nil {
		log.Fatal(err)
	}
}
开发者ID:ftrvxmtrx,项目名称:fd,代码行数:32,代码来源:sender_file.go


示例8: main

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
}
开发者ID:kapitanov,项目名称:logtail,代码行数:32,代码来源:logtail.go


示例9: createNewFiles

// createNewFiles creates all the log files for severity from sev down to infoLog.
// l.mu is held.
func (l *loggingT) createNewFiles(sev severity) error {
	l.mu.Lock()
	defer l.mu.Unlock()

	if !flag.Parsed() {
		return fmt.Errorf("ERROR: logging before flag.Parse: ")
	} else if l.toStderr {
		return nil
	}

	now := time.Now()
	// Files are created in decreasing severity order, so as soon as we find one
	// has already been created, we can stop.
	for s := sev; s >= infoLog; s-- {
		var sb *syncBuffer
		if l.file[s] == nil {
			sb = &syncBuffer{
				logger: l,
				sev:    s,
			}
		} else {
			if v, ok := l.file[s].(*syncBuffer); ok {
				sb = v
			}
		}

		if err := sb.rotateFile(now); err != nil {
			return err
		}
		l.file[s] = sb
	}

	return nil
}
开发者ID:chinanjjohn2012,项目名称:glog,代码行数:36,代码来源:glog.go


示例10: getFlags

// getFlags will define the variables that can be found in the command line (via the flags package)
func (c *GetConf) getFlags() error {
	// parse command line
	if flag.Parsed() {
		return errors.New("getconf.getFlags: flags already parsed")
	} else {
		//fl := flag.NewFlagSet("flag", flag.ContinueOnError)
		for _, v := range c.allOptions {
			if v.flagName == "" {
				v.flagName = strings.ToLower(v.name)
			}
			switch v.oType {
			case reflect.Int:
				flag.Int(v.flagName, 0, "")
			case reflect.Int64:
				flag.Int64(v.flagName, 0, "")
			case reflect.Float64:
				flag.Float64(v.flagName, 0, "")
			case reflect.Bool:
				flag.Bool(v.flagName, false, "")
			case reflect.String:
				flag.String(v.flagName, "", "")
			}
		}
	}
	return nil
}
开发者ID:jllopis,项目名称:try6,代码行数:27,代码来源:getconf.go


示例11: getConfigFilename

// getConfigFilename gets the absolute filename of the config file specified by
// the ConfigFilename flag, and whether it exists.
//
// If the (relative or absolute) ConfigFilename exists, then it is returned.
// If the ConfigFilename exists in a valid XDG path, then it is returned.
// If neither of those exist, the (relative or absolute) ConfigFilename is returned.
func getConfigFilename() (string, bool) {
	if !flag.Parsed() {
		flag.Parse()
	}

	cf := *configFilename
	if *configFilename == "" {
		cf = defaultConfigFilename
	}

	if filepath.IsAbs(cf) {
		// Absolute path specified; user knows what they want.
		_, err := os.Stat(cf)
		return cf, err == nil
	}

	absCF, err := filepath.Abs(cf)
	if err != nil {
		// syscall failure; treat as if file doesn't exist.
		return cf, false
	}
	if _, err := os.Stat(absCF); err == nil {
		// File exists on relative path.
		return absCF, true
	}

	if xdgCF, err := xdg.Config.Find(cf); err == nil {
		// File exists in an XDG directory.
		return xdgCF, true
	}

	// Default to relative path. This is probably what the user expects if
	// it wasn't found anywhere else.
	return absCF, false
}
开发者ID:TechEdge01,项目名称:cups-connector,代码行数:41,代码来源:config.go


示例12: New

// New returns prepares the *app.App and then
// returns a new Tester. It also disables
// logging in the App, since the Tester does
// its own logging.
func New(r Reporter, a *app.App) *Tester {
	if !flag.Parsed() {
		flag.Parse()
	}
	if *remoteHost == "" {
		if gaeLocal != nil && *gaeLocal {
			h := gaeLocalHost
			remoteHost = &h
		} else if gaeRemote != nil && *gaeRemote {
			h := internal.AppEngineAppHost()
			if h == "" {
				panic(errors.New("no application found in app.yaml - please, specify one to run remote tests"))
			}
			remoteHost = &h
		}
	}
	if *remoteHost != "" {
		r.Log(fmt.Sprintf("using host %s", *remoteHost))
	}
	if err := a.Prepare(); err != nil {
		r.Fatal(fmt.Errorf("error preparing app: %s", err))
	}
	a.Logger = nil
	return &Tester{r, a}
}
开发者ID:rainycape,项目名称:gondola,代码行数:29,代码来源:tester.go


示例13: init

func init() {
	flag.StringVar(&hostname, "host", "localhost", "Mongo DB host details.")
	flag.StringVar(&defaultVersion, "version", "New International Version (UK)", "Default Bible version to use, if none provided in request.")
	flag.StringVar(&defaultBook, "book", "Romans", "Default book to open, if none provided in request.")
	flag.StringVar(&defaultChapter, "chapter", "5", "Default chapter to open, if none provided in request.")
	flag.IntVar(&port, "port", 8998, "Port on which to bind the Rhema server.")
	var templatePath string
	flag.StringVar(&templatePath, "template", path.Join(path.Dir(os.Args[0]), "rhema.html"), "Path to the template file to use in generating web pages.")
	flag.Parse()
	if !flag.Parsed() {
		panic("Arguments could not be parsed.")
	}
	dat, e := ioutil.ReadFile(templatePath)
	if e != nil {
		panic(e)
	}
	page, e = template.New("Rhema").Parse(string(dat))
	if e != nil {
		panic(e)
	}
	session, e := mgo.Dial(hostname)
	if e != nil {
		panic(e)
	}
	bible = session.DB("bible")
	http.HandleFunc("/", rhemaHandler)
}
开发者ID:revence27,项目名称:Rhema,代码行数:27,代码来源:rhema.go


示例14: RegisterTaskQ

// RegisterTaskQ registers the TaskQ application and all its handler in the
// hive.
func RegisterTaskQ(h beehive.Hive, opts ...Option) error {
	if !flag.Parsed() {
		flag.Parse()
	}

	proto, err := NewProtoHandler(addr.Get(opts))
	if err != nil {
		return err
	}

	r := rate.Get(opts)
	taskq := h.NewApp("taskq", beehive.Persistent(repl.Get(opts)),
		beehive.OutRate(bucket.Rate(r), 2*r))
	taskq.Handle(Enque{}, EnQHandler{})
	taskq.Handle(Deque{}, DeQHandler{})
	taskq.Handle(Ack{}, AckHandler{})
	taskq.Handle(Timeout{}, TimeoutHandler{
		ExpDur: 60 * time.Second,
	})

	ah := &AckHTTPHandler{Hive: h}
	taskq.HandleHTTP("/{queue}/tasks/{id:[0-9]+}", ah).Methods("DELETE")
	dh := &DeQHTTPHandler{Hive: h}
	taskq.HandleHTTP("/{queue}/tasks/deque", dh).Methods("POST")
	eh := &EnQHTTPHandler{Hive: h}
	taskq.HandleHTTP("/{queue}/tasks", eh).Methods("POST")

	taskq.Detached(beehive.NewTimer(30*time.Second, func() {
		h.Emit(Timeout(time.Now()))
	}))
	taskq.Detached(proto)

	return nil
}
开发者ID:jyzhe,项目名称:beehive,代码行数:36,代码来源:server.go


示例15: main

func main() {
	// show usage and exit if
	//   -h or --help was passed
	//   the flags failed to parse
	//   there isn't a single arg left
	flag.Parse()
	if help || !flag.Parsed() || flag.NArg() != 1 {
		usage()
		os.Exit(1)
	}

	stringOfDigits := flag.Arg(0)
	barlength := getbarlength(stringOfDigits)
	if bar {
		fmt.Println(strings.Repeat("*", barlength))
	}
	for row := range bigDigits[0] {
		line := ""
		for column := range stringOfDigits {
			digit := stringOfDigits[column] - '0'
			if 0 <= digit && digit <= 9 {
				line += bigDigits[digit][row] + "  "
			} else {
				log.Fatal("invalid whole number")
			}
		}
		fmt.Println(line)
	}
	if bar {
		fmt.Println(strings.Repeat("*", barlength))
	}
}
开发者ID:Nordstrom,项目名称:programming_in_go_sg,代码行数:32,代码来源:bigdigits.go


示例16: Serve

// Serve starts kami with reasonable defaults.
// It works (exactly) like Goji, looking for Einhorn, the bind flag, GOJI_BIND...
func Serve() {
	if !flag.Parsed() {
		flag.Parse()
	}

	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", Handler())

	listener := bind.Default()
	log.Println("Starting kami on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("kami received signal, gracefully stopping") })
	graceful.PostHook(func() { log.Printf("kami stopped") })

	err := graceful.Serve(listener, http.DefaultServeMux)

	if err != nil {
		log.Fatal(err)
	}

	graceful.Wait()
}
开发者ID:gunosy,项目名称:kami,代码行数:27,代码来源:serve.go


示例17: init

func init() {
	if flag.Parsed() {
		return
	}
	level := log.LogNone
	levels := strings.SplitN(*loglevel, "|", -1)
	for _, v := range levels {
		switch v {
		case "none":
			level = level | log.LogNone
			break
		case "error":
			level = level | log.LogError
		case "warning":
			level = level | log.LogWarning
		case "message":
			level = level | log.LogMessage
		case "debug":
			level = level | log.LogDebug
		case "all":
			level = log.LogAll
		default:
		}
	}
	if err := log.Init(*logfile, level); err != nil {
		log.Error(err)
	}
}
开发者ID:mikespook,项目名称:wechat,代码行数:28,代码来源:log.go


示例18: Serve

func (s *Server) Serve() {
	if !flag.Parsed() {
		flag.Parse()
	}
	s.Init()
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", environment.Port()), http.HandlerFunc(s.PreServe)))
}
开发者ID:lucmichalski,项目名称:microservice,代码行数:7,代码来源:server.go


示例19: LoadApp

// LoadApp parses the commandline arguments and loads the config
func LoadApp() (*App, error) {

	var configFlag string
	var versionFlag bool

	if !flag.Parsed() {
		flag.StringVar(&configFlag, "config", "",
			"JSON config or file:// path to JSON config file.")
		flag.BoolVar(&versionFlag, "version", false, "Show version identifier and quit.")
		flag.Parse()
	}
	if versionFlag {
		fmt.Printf("Version: %s\nGitHash: %s\n", Version, GitHash)
		os.Exit(0)
	}
	if configFlag == "" {
		configFlag = os.Getenv("CONTAINERPILOT")
	}

	os.Setenv("CONTAINERPILOT_PID", fmt.Sprintf("%v", os.Getpid()))
	app, err := NewApp(configFlag)
	if err != nil {
		return nil, err
	}
	return app, nil
}
开发者ID:joyent,项目名称:containerpilot,代码行数:27,代码来源:app.go


示例20: DBCheck

func DBCheck() {
	// It only makes sense to do the DB check if the admin credentials are provided.

	if !flag.Parsed() {
		log.Fatal("Package jackdb requires you to parse the flags, preferably in your 'main' package.")
	}

	if adminSettings.Password == "" || adminSettings.Username == "" {
		// The admin credentials are not set.
		return
	}

	// The following variables should never vary.
	adminSettings.Database = "postgres"
	adminSettings.Host = sttngs.Host

	// Does the User exist?
	if exists, err := roleExists(); err != nil {
		log.Fatal("DBCHECK: An error occurred while checking for the role: " + err.Error())
	} else if !exists {
		if err := roleCreate(); err != nil {
			log.Fatal("DBCHECK: An error occurred while creating the role: " + err.Error())
		}
	}

	// Does the DB exist?
	if exists, err := dbExists(); err != nil {
		log.Fatal("DBCHECK: An error occurred while checking for the DB: " + err.Error())
	} else if !exists {
		if err := dbCreate(); err != nil {
			log.Fatal("DBCHECK: An error occurred while creating the DB: " + err.Error())
		}
	}
}
开发者ID:jackmanlabs,项目名称:jakdbpq,代码行数:34,代码来源:setup.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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