當前位置: 首頁>>代碼示例>>Golang>>正文


Golang pflag.StringVar函數代碼示例

本文整理匯總了Golang中github.com/ogier/pflag.StringVar函數的典型用法代碼示例。如果您正苦於以下問題:Golang StringVar函數的具體用法?Golang StringVar怎麽用?Golang StringVar使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了StringVar函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: main

func main() {
	var config Config
	flag.BoolVar(&DEBUG, "debug", false, "enable debug logging")
	flag.BoolVar(&QUIET, "quiet", false, "disable output")
	flag.StringVar(&config.FieldSep, "csv-fields-terminated-by", "\t", "field separator")
	flag.StringVar(&config.RowSep, "csv-records-terminated-by", "\n", "row separator")
	flag.StringVar(&config.NullString, "csv-null-string", "\\N", "output string for NULL values")
	flag.BoolVar(&config.DateEpoch, "epoch", true, "output datetime as epoch instead of RFC3339")
	defaults_file := flag.String("defaults-file", "my.cnf", "defaults file")
	defaults_group_suffix := flag.String("defaults-group-suffix", "", "defaults group suffix")
	format := flag.String("format", "json", "output format 'json' or 'csv'")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: mysqlcsvdump [options] database table > output.json\n\n")
		fmt.Fprintf(os.Stderr, "Reads connection info from ./my.cnf. Use '-' for table to send query in stdin\n\n")
		flag.PrintDefaults()
	}
	flag.Parse()

	args := flag.Args()
	if len(args) < 2 {
		flag.Usage()
		os.Exit(1)
	}
	dsn := getDSN(*defaults_file, "client"+*defaults_group_suffix, args[0])
	rows := getRows(dsn, args[1])
	if *format == "json" {
		NewJsonWriter(&config).WriteRows(rows)
	} else {
		NewCsvWriter(&config).WriteRows(rows)
	}
}
開發者ID:hzarka,項目名稱:mysqlbqdump,代碼行數:31,代碼來源:mysqlbqdump.go

示例2: main

// main takes care of how to run when called via the CLI
func main() {
	// Add MongoDB flags to the parser
	flag.StringVar(&conf.Config.MongoURI, "MongoURI", conf.Config.MongoURI, "MongoDB server URI")
	flag.StringVar(&conf.Config.MongoDatabase, "MongoDatabase", conf.Config.MongoDatabase, "MongoDB database")

	// Make a new server.
	server := goserv.NewServer(&conf.Config.BaseConfiguration)
	wsContainer := restful.NewContainer()
	p := api.Product{}
	p.Register(wsContainer)

	status := api.StatusResource{}
	status.Register(wsContainer)

	groups := api.GroupsResource{}
	groups.Register(wsContainer)

	hash := api.HashResource{}
	hash.Register(wsContainer)

	wsContainer.ServiceErrorHandler(api.ErrorHandler)

	// Enable swagger
	/*config := swagger.Config{
		WebServices: wsContainer.RegisteredWebServices(),
		ApiPath:     "/service/v3/apidocs.json",
	}
	swagger.RegisterSwaggerService(config, wsContainer)
	*/
	// Set the handler to our gorilla mux router wrapped with LogAccess
	server.Handler = goserv.LogAccess(wsContainer)
	goserv.Logger.Fatal(server.ListenAndServe())
}
開發者ID:jasinner,項目名稱:victims-api,代碼行數:34,代碼來源:main.go

示例3: parseFlags

func (cm *ConfigManager) parseFlags() {
	pflag.StringVarP(&cm.Flags.ConfigFile, "configfile", "c", DefaultConfigFile, "Path to config")
	pflag.StringVarP(&cm.Flags.DestHost, "dest-host", "d", "", "Destination syslog hostname or IP")
	pflag.IntVarP(&cm.Flags.DestPort, "dest-port", "p", 0, "Destination syslog port")
	if utils.CanDaemonize {
		pflag.BoolVarP(&cm.Flags.NoDaemonize, "no-detach", "D", false, "Don't daemonize and detach from the terminal")
	} else {
		cm.Flags.NoDaemonize = true
	}
	pflag.StringVarP(&cm.Flags.Facility, "facility", "f", "user", "Facility")
	pflag.StringVar(&cm.Flags.Hostname, "hostname", "", "Local hostname to send from")
	pflag.StringVar(&cm.Flags.PidFile, "pid-file", "", "Location of the PID file")
	// --parse-syslog
	pflag.StringVarP(&cm.Flags.Severity, "severity", "s", "notice", "Severity")
	// --strip-color
	pflag.BoolVar(&cm.Flags.UseTCP, "tcp", false, "Connect via TCP (no TLS)")
	pflag.BoolVar(&cm.Flags.UseTLS, "tls", false, "Connect via TCP with TLS")
	pflag.BoolVar(&cm.Flags.Poll, "poll", false, "Detect changes by polling instead of inotify")
	pflag.Var(&cm.Flags.RefreshInterval, "new-file-check-interval", "How often to check for new files")
	_ = pflag.Bool("no-eventmachine-tail", false, "No action, provided for backwards compatibility")
	_ = pflag.Bool("eventmachine-tail", false, "No action, provided for backwards compatibility")
	pflag.StringVar(&cm.Flags.DebugLogFile, "debug-log-cfg", "", "the debug log file")
	pflag.StringVar(&cm.Flags.LogLevels, "log", "<root>=INFO", "\"logging configuration <root>=INFO;first=TRACE\"")
	pflag.Parse()
	cm.FlagFiles = pflag.Args()
}
開發者ID:ecorvo,項目名稱:remote_syslog2,代碼行數:26,代碼來源:config_manager.go

示例4: parseFlags

func parseFlags() (*cmdConfig, *busltee.Config, error) {
	publisherConf := &busltee.Config{}
	cmdConf := &cmdConfig{}

	cmdConf.RollbarEnvironment = os.Getenv("ROLLBAR_ENVIRONMENT")
	cmdConf.RollbarToken = os.Getenv("ROLLBAR_TOKEN")

	// Connection related flags
	flag.BoolVarP(&publisherConf.Insecure, "insecure", "k", false, "allows insecure SSL connections")
	flag.IntVar(&publisherConf.Retry, "retry", 5, "max retries for connect timeout errors")
	flag.IntVar(&publisherConf.StreamRetry, "stream-retry", 60, "max retries for streamer disconnections")
	flag.Float64Var(&publisherConf.Timeout, "connect-timeout", 1, "max number of seconds to connect to busl URL")

	// Logging related flags
	flag.StringVar(&publisherConf.LogPrefix, "log-prefix", "", "log prefix")
	flag.StringVar(&publisherConf.LogFile, "log-file", "", "log file")
	flag.StringVar(&publisherConf.RequestID, "request-id", "", "request id")

	if flag.Parse(); len(flag.Args()) < 2 {
		return nil, nil, errors.New("insufficient args")
	}

	publisherConf.URL = flag.Arg(0)
	publisherConf.Args = flag.Args()[1:]

	return cmdConf, publisherConf, nil
}
開發者ID:heroku,項目名稱:busl,代碼行數:27,代碼來源:main.go

示例5: main

// main takes care of how to run when called via the CLI
func main() {
	// Add MongoDB flags to the parser
	flag.StringVar(&conf.Config.MongoURI, "MongoURI", conf.Config.MongoURI, "MongoDB server URI")
	flag.StringVar(&conf.Config.MongoDatabase, "MongoDatabase", conf.Config.MongoDatabase, "MongoDB database")

	// Make a new server.
	server := goserv.NewServer(&conf.Config.BaseConfiguration)
	wsContainer := restful.NewContainer()
	p := api.Product{}
	p.Register(wsContainer)

	status := api.StatusResource{}
	status.Register(wsContainer)

	groups := api.GroupsResource{}
	groups.Register(wsContainer)

	hash := api.HashResource{}
	hash.Register(wsContainer)

	coordinates := api.CoordinatesResource{}
	coordinates.Register(wsContainer)

	wsContainer.ServiceErrorHandler(api.ErrorHandler)

	// Set the handler to our gorilla mux router wrapped with LogAccess
	server.Handler = goserv.LogAccess(wsContainer)
	goserv.Logger.Fatal(server.ListenAndServe())
}
開發者ID:ashcrow,項目名稱:victims-api,代碼行數:30,代碼來源:main.go

示例6: Go

func Go() {
	smtpAddr := "localhost:1025"

	goflag := false
	for _, g := range os.Args[1:] {
		if strings.HasPrefix(g, "-") && !strings.HasPrefix(g, "--") {
			if strings.HasPrefix(g, "-from ") || strings.HasPrefix(g, "-from=") ||
				strings.HasPrefix(g, "-smtp-addr ") || strings.HasPrefix(g, "-smtp-addr=") {
				goflag = true
				break
			}
		}
	}

	host, err := os.Hostname()
	if err != nil {
		host = "localhost"
	}

	username := "nobody"
	user, err := user.Current()
	if err == nil && user != nil && len(user.Username) > 0 {
		username = user.Username
	}

	fromAddr := username + "@" + host
	var recip []string

	if goflag {
		flag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address")
		flag.StringVar(&fromAddr, "from", fromAddr, "SMTP sender")

		flag.Parse()
		recip = flag.Args()
	} else {
		pflag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address")
		pflag.StringVarP(&fromAddr, "from", "f", fromAddr, "SMTP sender")

		pflag.Parse()
		recip = pflag.Args()
	}

	if len(recip) == 0 {
		fmt.Fprintln(os.Stderr, "missing recipient")
		os.Exit(10)
	}

	body, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error reading stdin")
		os.Exit(11)
	}

	err = smtp.SendMail(smtpAddr, nil, fromAddr, recip, body)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error sending mail")
		log.Fatal(err)
	}

}
開發者ID:OpenConceptConsulting,項目名稱:mhsendmail,代碼行數:60,代碼來源:cmd.go

示例7: Run

func (mmsd *mmsdService) Run() {
	flag.BoolVarP(&mmsd.Verbose, "verbose", "v", mmsd.Verbose, "Set verbosity level")
	flag.IPVar(&mmsd.MarathonIP, "marathon-ip", mmsd.MarathonIP, "Marathon endpoint TCP IP address")
	flag.UintVar(&mmsd.MarathonPort, "marathon-port", mmsd.MarathonPort, "Marathon endpoint TCP port number")
	flag.DurationVar(&mmsd.ReconnectDelay, "reconnect-delay", mmsd.ReconnectDelay, "Marathon reconnect delay")
	flag.StringVar(&mmsd.RunStateDir, "run-state-dir", mmsd.RunStateDir, "Path to directory to keep run-state")
	flag.StringVar(&mmsd.FilterGroups, "filter-groups", mmsd.FilterGroups, "Application group filter")
	flag.IPVar(&mmsd.ManagedIP, "managed-ip", mmsd.ManagedIP, "IP-address to manage for mmsd")
	flag.BoolVar(&mmsd.GatewayEnabled, "enable-gateway", mmsd.GatewayEnabled, "Enables gateway support")
	flag.IPVar(&mmsd.GatewayAddr, "gateway-bind", mmsd.GatewayAddr, "gateway bind address")
	flag.UintVar(&mmsd.GatewayPortHTTP, "gateway-port-http", mmsd.GatewayPortHTTP, "gateway port for HTTP")
	flag.UintVar(&mmsd.GatewayPortHTTPS, "gateway-port-https", mmsd.GatewayPortHTTPS, "gateway port for HTTPS")
	flag.BoolVar(&mmsd.FilesEnabled, "enable-files", mmsd.FilesEnabled, "enables file based service discovery")
	flag.BoolVar(&mmsd.UDPEnabled, "enable-udp", mmsd.UDPEnabled, "enables UDP load balancing")
	flag.BoolVar(&mmsd.TCPEnabled, "enable-tcp", mmsd.TCPEnabled, "enables haproxy TCP load balancing")
	flag.BoolVar(&mmsd.LocalHealthChecks, "enable-health-checks", mmsd.LocalHealthChecks, "Enable local health checks (if available) instead of relying on Marathon health checks alone.")
	flag.StringVar(&mmsd.HaproxyBin, "haproxy-bin", mmsd.HaproxyBin, "path to haproxy binary")
	flag.StringVar(&mmsd.HaproxyTailCfg, "haproxy-cfgtail", mmsd.HaproxyTailCfg, "path to haproxy tail config file")
	flag.IPVar(&mmsd.ServiceAddr, "haproxy-bind", mmsd.ServiceAddr, "haproxy management port")
	flag.UintVar(&mmsd.HaproxyPort, "haproxy-port", mmsd.HaproxyPort, "haproxy management port")
	flag.BoolVar(&mmsd.DnsEnabled, "enable-dns", mmsd.DnsEnabled, "Enables DNS-based service discovery")
	flag.UintVar(&mmsd.DnsPort, "dns-port", mmsd.DnsPort, "DNS service discovery port")
	flag.BoolVar(&mmsd.DnsPushSRV, "dns-push-srv", mmsd.DnsPushSRV, "DNS service discovery to also push SRV on A")
	flag.StringVar(&mmsd.DnsBaseName, "dns-basename", mmsd.DnsBaseName, "DNS service discovery's base name")
	flag.DurationVar(&mmsd.DnsTTL, "dns-ttl", mmsd.DnsTTL, "DNS service discovery's reply message TTL")
	showVersionAndExit := flag.BoolP("version", "V", false, "Shows version and exits")

	flag.Usage = func() {
		showVersion()
		fmt.Fprintf(os.Stderr, "\nUsage: mmsd [flags ...]\n\n")
		flag.PrintDefaults()
		fmt.Fprintf(os.Stderr, "\n")
	}

	flag.Parse()

	if *showVersionAndExit {
		showVersion()
		os.Exit(0)
	}

	mmsd.setupHandlers()
	mmsd.setupEventBusListener()
	mmsd.setupHttpService()

	<-mmsd.quitChannel
}
開發者ID:dawanda,項目名稱:mmsd,代碼行數:47,代碼來源:main.go

示例8: NewServer

// NewServer creates a new http.Server instance based off the BaseConfiguration.
// NewServer also handles reading the TOML configuration file and
// providing/reading the command line flags. Because of this
// NewServer should always be called after all flags have been defined.
func NewServer(conf *BaseConfiguration) http.Server {
	// TOML configuration file can overwrite defaults
	tomlData, err := ioutil.ReadFile(os.Args[len(os.Args)-1])
	if err != nil {
		defer Logger.Info("No conf. Skipping.")
	} else {
		if _, err := toml.Decode(string(tomlData), &conf); err != nil {
			defer Logger.Errorf("Configuration file could not be decoded. %s. Exiting...", err)
		}
	}
	// Flags can override config items
	// Server flags
	flag.StringVar(&conf.BindAddress, "BindAddress", conf.BindAddress, "Bind address.")
	flag.IntVar(&conf.BindPort, "BindPort", conf.BindPort, "HTTP bind port.")
	flag.DurationVar(&conf.ReadTimeout, "ReadTimeout", conf.ReadTimeout, "Read timeout.")
	flag.DurationVar(&conf.WriteTimeout, "WriteTimeout", conf.WriteTimeout, "Write timeout.")
	flag.IntVar(&conf.MaxHeaderBytes, "MaxHeaderBytes", conf.MaxHeaderBytes, "Max header bytes.")

	// Server Logger flags
	flag.StringVar(&conf.LogLevel, "LogLevel", conf.LogLevel, "Log level.")
	flag.StringVar(&conf.LogFile, "LogFile", conf.LogFile, "Log file.")

	// TLS related flags
	flag.IntVar(&conf.BindHttpsPort, "BindHttpsPort", conf.BindHttpsPort, "HTTPS bind port.")
	flag.StringVar(&conf.CertFile, "CertFile", conf.CertFile, "Cert file.")
	flag.StringVar(&conf.KeyFile, "KeyFile", conf.KeyFile, "Key file.")
	flag.Parse()

	// Logging specific work also injecting the logrus log into the Servers errorlog
	// BUG(ashcrow): This needs work!!!
	makeLogger(conf)
	Logger.Debugf("Final configuration: %+v", conf)
	w := Logger.Writer()
	defer w.Close()
	ServerErrorLogger = *log.New(w, "ServerErrorLogger", log.Lshortfile)
	// -------------

	// Return the configured http.Server
	return http.Server{
		Addr:           fmt.Sprintf("%s:%d", conf.BindAddress, conf.BindPort),
		ReadTimeout:    conf.ReadTimeout,
		WriteTimeout:   conf.WriteTimeout,
		MaxHeaderBytes: conf.MaxHeaderBytes,
		ErrorLog:       &ServerErrorLogger,
	}
}
開發者ID:pombredanne,項目名稱:go-serv,代碼行數:50,代碼來源:server.go

示例9: init

func init() {
	flag.StringVarP(&flagPlatform, "platform", "p", "linux",
		"the platform to build for")
	flag.StringVarP(&flagArch, "arch", "a", "amd64",
		"the architecture to build for")
	flag.StringVar(&flagBuildDir, "build-dir", "/tmp/sbuild",
		"the directory to use as a build directory")
	flag.BoolVarP(&flagVerbose, "verbose", "v", false, "be verbose")
}
開發者ID:andrew-d,項目名稱:sbuild,代碼行數:9,代碼來源:main.go

示例10: main

func main() {
	flag.Usage = func() {
		fmt.Fprint(os.Stderr, Usage)
	}

	flag.IntVarP(&options.Port, "port", "p", 8080, "")
	flag.StringVar(&options.CustomCSS, "custom-css", "", "")

	flag.Parse()

	options.Dir = flag.Arg(0)

	if options.Dir == "" {
		flag.Usage()
		os.Exit(1)
	}

	log.Println("Serving wiki from", options.Dir)

	// Parse base template
	var err error
	options.template, err = template.New("base").Parse(Template)
	if err != nil {
		log.Fatalln("Error parsing HTML template:", err)
	}

	// Trim trailing slash from root path
	if strings.HasSuffix(options.Dir, "/") {
		options.Dir = options.Dir[:len(options.Dir)-1]
	}

	// Verify that the wiki folder exists
	_, err = os.Stat(options.Dir)
	if os.IsNotExist(err) {
		log.Fatalln("Directory not found")
	}

	// Check if the wiki folder is a Git repository
	options.git = IsGitRepository(options.Dir)
	if options.git {
		log.Println("Git repository found in directory")
	} else {
		log.Println("No git repository found in directory")
	}

	http.Handle("/api/diff/", commonHandler(DiffHandler))
	http.Handle("/", commonHandler(WikiHandler))

	log.Println("Listening on:", options.Port)
	http.ListenAndServe(fmt.Sprintf(":%d", options.Port), nil)
}
開發者ID:sguzwf,項目名稱:go-wiki,代碼行數:51,代碼來源:main.go

示例11: init

func init() {
	flag.BoolVarP(&flagVerbose, "verbose", "v", false, "be more verbose")
	flag.BoolVarP(&flagQuiet, "quiet", "q", false, "be quiet")
	flag.BoolVarP(&flagTrace, "trace", "t", false, "trace bytes copied")

	flag.StringVarP(&flagHost, "host", "h", "", "host to listen on")
	flag.Uint16VarP(&flagPort, "port", "p", 8000, "port to listen on")
	flag.VarP(&flagAllowedSourceIPs, "source-ips", "s",
		"valid source IP addresses (if none given, all allowed)")
	flag.VarP(&flagAllowedDestinationIPs, "dest-ips", "d",
		"valid destination IP addresses (if none given, all allowed)")

	flag.StringVar(&flagRemoteListener, "remote-listener", "",
		"open the SOCKS port on the remote address (e.g. ssh://user:[email protected]:port)")
}
開發者ID:bmbernie,項目名稱:socks,代碼行數:15,代碼來源:main.go

示例12: init

func init() {
	pflag.DurationVar(&config.TickerTime, "ticker-time", 60*time.Second, "Ticker time.")
	pflag.DurationVar(&config.DeleteTime, "delete-time", 60*time.Minute, "Time before deleting undesired units.")
	pflag.DurationVar(&config.UpdateCooldownTime, "update-cooldown-time", 15*time.Minute, "Time between updates of changed units.")

	pflag.StringVar(&config.MachineTag, "machine-tag", "", "The machine-tag to filter for.")
	pflag.StringVar(&config.UnitTemplate, "unit-template", "", "The template to render for new units. Prefix with @ to load from a file.")
	pflag.StringVar(&config.UnitPrefix, "unit-prefix", "", "The prefix for the units to identify.")

	pflag.StringVar(&glogFlags.logToStderr, "logtostderr", "true", "log to standard error instead of files")
	pflag.StringVar(&glogFlags.alsoLogToStderr, "alsologtostderr", "false", "log to standard error as well as files")
	pflag.StringVarP(&glogFlags.verbosity, "verbose", "v", "1", "log level for V logs")
	pflag.StringVar(&glogFlags.vmodule, "vmodule", "", "comma-separated list of pattern=N settings for file-filtered logging")
	pflag.StringVar(&glogFlags.logBacktraceAt, "log_backtrace_at", "", "when logging hits line file:N, emit a stack trace")
}
開發者ID:giantswarm,項目名稱:fleet-unit-replicator,代碼行數:15,代碼來源:main.go

示例13: init

func init() {
	pflag.DurationVar(&config.TickerTime, "ticker-time", 15*time.Minute, "Ticker time.")
	pflag.BoolVar(&config.DryRun, "dry-run", true, "Write to STDOUT instead of InfluxDB")
	pflag.IntVar(&config.OWMcityID, "owm-city-id", 0, "Open Weather Map city ID")

	pflag.IntVar(&config.InfluxPort, "influx-port", 8086, "InfluxDB Port")
	pflag.StringVar(&config.InfluxHost, "influx-host", "localhost", "InfluxDB Port")
	pflag.StringVar(&config.InfluxUser, "influx-user", "", "InfluxDB User")
	pflag.StringVar(&config.InfluxDB, "influx-db", "", "InfluxDB Database")
	pflag.StringVar(&config.InfluxPassword, "influx-password", "", "InfluxDB Password")
	pflag.StringVar(&config.InfluxRetention, "influx-retention", "default", "InfluxDB Retention")

	pflag.StringVar(&config.DhtType, "dht-type", "DHT22", "DHT Type (DHT11, DHT22)")
	pflag.IntVar(&config.DhtPin, "dht-pin", 4, "Pin Number DHT Data is connected to")
	pflag.BoolVar(&config.DHTPerf, "dht-perf", false, "Run DHT read in Boost Performance Mode - true will result in needing sudo")
	pflag.IntVar(&config.DhtRetries, "dht-retries", 15, "Number of reading data retries")

}
開發者ID:Nesurion,項目名稱:temperature-go,代碼行數:18,代碼來源:main.go

示例14: Go

// Go runs the MailHog sendmail replacement.
func Go() {
	smtpAddr := "localhost:1025"

	goflag := false
	for _, g := range os.Args[1:] {
		if strings.HasPrefix(g, "-") && !strings.HasPrefix(g, "--") {
			if strings.HasPrefix(g, "-from ") || strings.HasPrefix(g, "-from=") ||
				strings.HasPrefix(g, "-smtp-addr ") || strings.HasPrefix(g, "-smtp-addr=") {
				goflag = true
				break
			}
		}
	}

	host, err := os.Hostname()
	if err != nil {
		host = "localhost"
	}

	username := "nobody"
	user, err := user.Current()
	if err == nil && user != nil && len(user.Username) > 0 {
		username = user.Username
	}

	fromAddr := username + "@" + host
	var recip []string

	if goflag {
		flag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address")
		flag.StringVar(&fromAddr, "from", fromAddr, "SMTP sender")

		flag.Parse()
		recip = flag.Args()
	} else {
		pflag.StringVar(&smtpAddr, "smtp-addr", smtpAddr, "SMTP server address")
		pflag.StringVarP(&fromAddr, "from", "f", fromAddr, "SMTP sender")

		pflag.Parse()
		recip = pflag.Args()
	}

	body, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error reading stdin")
		os.Exit(11)
	}

	if len(recip) == 0 {
		// We only need to parse the message to get a recipient if none where
		// provided on the command line.
		//		re := regexp.MustCompile("(?im)^To: (.*)\r*\n$")
		re := regexp.MustCompile("(?im)^To: (.*)\r*$")
		n := bytes.IndexByte(body, 0)
		var bodyStr string
		if n < 0 {
			bodyStr = string(body)
		} else {
			bodyStr = string(body[:n])
		}
		includedRecip := re.FindAllString(bodyStr, -1)
		if includedRecip == nil {
			fmt.Fprintln(os.Stderr, "missing recipient")
			os.Exit(10)
		}
		newRecip := make([]string, len(recip), len(recip)+len(includedRecip))
		copy(newRecip, recip)
		recip = append(newRecip, includedRecip...)
	}

	err = smtp.SendMail(smtpAddr, nil, fromAddr, recip, body)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error sending mail")
		log.Fatal(err)
	}

}
開發者ID:iefbr14,項目名稱:mhsendmail,代碼行數:78,代碼來源:cmd.go

示例15: config

// Read configuration from both profile and flags. Flags override profile.
func config() error {
	var err error
	if B2D.Dir, err = getCfgDir(".boot2docker"); err != nil {
		return fmt.Errorf("failed to get current directory: %s", err)
	}

	filename := os.Getenv("BOOT2DOCKER_PROFILE")
	if filename == "" {
		filename = filepath.Join(B2D.Dir, "profile")
	}
	profile, err := getProfile(filename)
	if err != nil && !os.IsNotExist(err) { // undefined/empty profile works
		return err
	}

	if p := os.Getenv("VBOX_INSTALL_PATH"); p != "" && runtime.GOOS == "windows" {
		B2D.VBM = profile.Get("", "vbm", filepath.Join(p, "VBoxManage.exe"))
	} else {
		B2D.VBM = profile.Get("", "vbm", "VBoxManage")
	}

	B2D.SSH = profile.Get("", "ssh", "ssh")
	B2D.VM = profile.Get("", "vm", "boot2docker-vm")
	B2D.ISO = profile.Get("", "iso", filepath.Join(B2D.Dir, "boot2docker.iso"))

	if diskSize, err := strconv.ParseUint(profile.Get("", "disksize", "20000"), 10, 32); err != nil {
		return fmt.Errorf("invalid disk image size: %s", err)
	} else {
		B2D.DiskSize = uint(diskSize)
	}

	if memory, err := strconv.ParseUint(profile.Get("", "memory", "1024"), 10, 32); err != nil {
		return fmt.Errorf("invalid memory size: %s", err)
	} else {
		B2D.Memory = uint(memory)
	}

	if sshPort, err := strconv.ParseUint(profile.Get("", "sshport", "2022"), 10, 16); err != nil {
		return fmt.Errorf("invalid SSH port: %s", err)
	} else {
		B2D.SSHPort = uint16(sshPort)
	}

	if dockerPort, err := strconv.ParseUint(profile.Get("", "dockerport", "4243"), 10, 16); err != nil {
		return fmt.Errorf("invalid DockerPort: %s", err)
	} else {
		B2D.DockerPort = uint16(dockerPort)
	}

	// Host only networking settings
	B2D.HostIP = profile.Get("", "hostiP", "192.168.59.3")
	B2D.DHCPIP = profile.Get("", "dhcpip", "192.168.59.99")
	B2D.NetworkMask = profile.Get("", "netmask", "255.255.255.0")
	B2D.LowerIPAddress = profile.Get("", "lowerip", "192.168.59.103")
	B2D.UpperIPAddress = profile.Get("", "upperip", "192.168.59.254")
	B2D.DHCPEnabled = profile.Get("", "dhcp", "Yes")

	// Commandline flags override profile settings.
	flag.StringVar(&B2D.VBM, "vbm", B2D.VBM, "Path to VirtualBox management utility")
	flag.StringVar(&B2D.SSH, "ssh", B2D.SSH, "Path to SSH client utility")
	flag.StringVarP(&B2D.Dir, "dir", "d", B2D.Dir, "boot2docker config directory")
	flag.StringVar(&B2D.ISO, "iso", B2D.ISO, "Path to boot2docker ISO image")
	flag.UintVarP(&B2D.DiskSize, "disksize", "s", B2D.DiskSize, "boot2docker disk image size (in MB)")
	flag.UintVarP(&B2D.Memory, "memory", "m", B2D.Memory, "Virtual machine memory size (in MB)")
	flag.Var(newUint16Value(B2D.SSHPort, &B2D.SSHPort), "sshport", "Host SSH port (forward to port 22 in VM)")
	flag.Var(newUint16Value(B2D.DockerPort, &B2D.DockerPort), "dockerport", "Host Docker port (forward to port 4243 in VM)")
	flag.StringVar(&B2D.HostIP, "hostip", B2D.HostIP, "VirtualBox host-only network IP address")
	flag.StringVar(&B2D.NetworkMask, "netmask", B2D.NetworkMask, "VirtualBox host-only network mask")
	flag.StringVar(&B2D.DHCPEnabled, "dhcp", B2D.DHCPEnabled, "Enable VirtualBox host-only network DHCP")
	flag.StringVar(&B2D.DHCPIP, "dhcpip", B2D.DHCPIP, "VirtualBox host-only network DHCP server address")
	flag.StringVar(&B2D.LowerIPAddress, "lowerip", B2D.LowerIPAddress, "VirtualBox host-only network DHCP lower bound")
	flag.StringVar(&B2D.UpperIPAddress, "upperip", B2D.UpperIPAddress, "VirtualBox host-only network DHCP upper bound")

	flag.Parse()

	// Name of VM is the second argument.
	if vm := flag.Arg(1); vm != "" {
		B2D.VM = vm
	}
	return nil
}
開發者ID:polvi,項目名稱:boot2docker-cli,代碼行數:82,代碼來源:config.go


注:本文中的github.com/ogier/pflag.StringVar函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。