本文整理汇总了Golang中flag.Lookup函数的典型用法代码示例。如果您正苦于以下问题:Golang Lookup函数的具体用法?Golang Lookup怎么用?Golang Lookup使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Lookup函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: init
//####################################//
// Code
//====================================//
// Init code
func init() {
// FIXME init flags
const (
flagDef_Debug = false
flagDescDebug = " -debug enable debug"
flagDef_Quiet = false
flagDescQuiet = "-q -quiet suppress output"
)
flag.BoolVar(&flagDebug, "debug", false, flagDescDebug)
flag.BoolVar(&flagQuiet, "q", false, flagDescQuiet)
flag.BoolVar(&flagQuiet, "quiet", false, flagDescQuiet)
//----------------------------------//
// Help
// FIXME update help
flag.Usage = func() {
usage := `Usage: %s [options]
Options:
` + flag.Lookup("q").Usage + `
` + flag.Lookup("debug").Usage + `
No more options for now.
MIT, BSD or something. There is no help.
`
fmt.Fprintf(os.Stderr, usage, os.Args[0])
}
//----------------------------------//
}
开发者ID:Tracerneo,项目名称:WebServerTemplate,代码行数:32,代码来源:main.go
示例2: TestRegisterFlags
func TestRegisterFlags(t *testing.T) {
c := &Config{
DHTRouters: "example.router.com:6060",
MaxNodes: 2020,
CleanupPeriod: time.Second,
SavePeriod: time.Second * 2,
RateLimit: 999,
}
RegisterFlags(c)
if flag.Lookup("routers").DefValue != c.DHTRouters {
t.Fatal("Incorrect routers flag")
}
if flag.Lookup("maxNodes").DefValue != strconv.FormatInt(int64(c.MaxNodes), 10) {
t.Fatal("Incorrect maxNodes flag")
}
if flag.Lookup("cleanupPeriod").DefValue != c.CleanupPeriod.String() {
t.Fatal("Incorrect cleanupPeriod flag")
}
if flag.Lookup("savePeriod").DefValue != c.SavePeriod.String() {
t.Fatal("Incorrect routers flag")
}
if flag.Lookup("rateLimit").DefValue != strconv.FormatInt(c.RateLimit, 10) {
t.Fatal("Incorrect routers flag")
}
}
开发者ID:peterlee2008,项目名称:dht,代码行数:25,代码来源:dht_test.go
示例3: main
func main() {
flag.Parse()
if *cliVersion {
fmt.Println(flag.Lookup("version").Usage)
exit(0)
return
}
if *cliHelp {
fmt.Println(flag.Lookup("help").Usage)
exit(0)
return
}
var res beatsone.BeatsOne
var err error
if *cliSchedule {
res, err = beatsone.GetSchedule()
} else {
res, err = beatsone.GetNowPlaying()
}
if err != nil {
fmt.Println(err)
exit(1)
}
if *cliJSON {
fmt.Println(res.JSONString())
} else {
fmt.Println(res.String())
}
exit(0)
return
}
开发者ID:hygerth,项目名称:beatsone,代码行数:32,代码来源:main.go
示例4: Setup
func (p *GitParser) Setup() {
executable := flag.Lookup("executable").Value.String()
out := flag.Lookup("out").Value.String()
if out == "<STDOUT>" {
out = "REVISION.json"
}
hook := executable + " -out=\"" + out + "\"; # scm-status hook\r\n"
hook_dir := strings.Join([]string{p.Dir(), ".git", "hooks"}, path_separator)
filenames := []string{
hook_dir + path_separator + "post-checkout",
hook_dir + path_separator + "post-merge",
hook_dir + path_separator + "post-commit",
}
for _, filename := range filenames {
fp, _ := os.OpenFile(filename, os.O_RDWR+os.O_APPEND+os.O_CREATE, 0775)
_, _ = fp.WriteString(hook)
fp.Close()
}
}
开发者ID:jimmysawczuk,项目名称:scm-status,代码行数:26,代码来源:git.go
示例5: main
func main() {
flag.Parse()
if flagOne == "" {
fmt.Fprintf(os.Stdout, "Usage of cody.guo ok %s:\n", os.Args[0])
flag.PrintDefaults()
os.Exit(1)
}
fmt.Println("参数数量:", flag.NFlag())
oneFlag := flag.Lookup("one")
fmt.Println(oneFlag.Name, oneFlag.Value)
// fmt.Println(len(os.Args))
if debug {
fmt.Println("debug is on.")
} else {
fmt.Println("debug is off.")
}
fmt.Println(flagOne)
debugFlag := flag.Lookup("d")
fmt.Println(debugFlag.Name, debugFlag.Value)
}
开发者ID:CodyGuo,项目名称:Go-Cody,代码行数:28,代码来源:main.go
示例6: fakeRequest
func fakeRequest() {
flag.Lookup("alsologtostderr").Value.Set("true")
flag.Lookup("log_dir").Value.Set("./log_dir")
flag.Parse()
glog.Infoln("begin fake..")
// test_uid := "45529"
host := "0.0.0.0"
port := "12231"
dirver_trail_json := `[{"lat":"33.33066","lng":"121.284148","t":1472338663}]`
driver_trail_form := url.Values{
"session_id": []string{"test_uid"},
"json": []string{dirver_trail_json},
"city": []string{"上海"},
}
ticker := time.NewTicker(time.Second * 5)
for t := range ticker.C {
resp, err := http.PostForm(fmt.Sprintf("http://%s:%s/driver/trail", host, port), driver_trail_form)
if err != nil {
glog.Errorf("at %s, PostForm-err: %s\n", t, err)
}
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
if err != nil {
glog.Errorf("at %s, ioutil.ReadAll-err: %s\n", t, err)
}
glog.Infof("at %s, fake post, fadback is %s", t, string(resp_body))
}
}
开发者ID:zykzhang,项目名称:practice,代码行数:29,代码来源:main.go
示例7: main
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()
}
开发者ID:owlfish,项目名称:forestbus-server,代码行数:59,代码来源:server.go
示例8: main
func main() {
settings.Init()
flag.Parse()
if len(os.Args) == 1 {
flag.Usage()
return
}
if flag.Lookup("run") == nil && flag.Lookup("svcctl") == nil && flag.Lookup("help") == nil && flag.Lookup("console") == nil {
flag.Usage()
return
}
if *help {
flag.Usage()
return
}
LogFile, err := os.OpenFile(settings.Log.File, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
if err != nil {
fmt.Println(err)
return
}
p := &Program{
Logger: log.New(LogFile, "[filesync]", log.Ldefault|log.Lmicroseconds),
}
s, err := svc.New(p, &svc.Config{
Name: "Filesync",
DisplayName: "FileSync Service",
Description: "Filesync is a simple tool to sync files between multiple directory pairs.",
Arguments: []string{"-run"},
})
if err != nil {
fmt.Println(err.Error())
return
}
if *run {
if *console {
p.Logger = log.New(os.Stdout, "[filesync]", log.Ldefault|log.Lmicroseconds)
p.run()
return
}
err := s.Run()
fmt.Println("run with error: ", err)
return
}
Actions := strings.Split(*controls, ",")
for _, action := range Actions {
err := svc.Control(s, action)
fmt.Println(err)
}
}
开发者ID:Felamande,项目名称:filesync,代码行数:59,代码来源:sync.go
示例9: main
func main() {
flag.Parse()
flagsOk := true
if flag.Lookup("project").Value.String() == "" {
fmt.Fprintf(os.Stderr, "Flag --project is required\n")
flagsOk = false
}
var sourceFlagCount int
if flag.Lookup("dataset").Value.String() != "" {
sourceFlagCount++
}
if flag.Lookup("jobid").Value.String() != "" {
sourceFlagCount++
}
if sourceFlagCount != 1 {
fmt.Fprintf(os.Stderr, "Exactly one of --dataset or --jobid must be set\n")
flagsOk = false
}
if !flagsOk {
os.Exit(1)
}
tableRE, err := regexp.Compile(*table)
if err != nil {
fmt.Fprintf(os.Stderr, "--table is not a valid regular expression: %q\n", *table)
os.Exit(1)
}
httpClient, err := google.DefaultClient(context.Background(), bigquery.Scope)
if err != nil {
log.Fatalf("Creating http client: %v", err)
}
client, err := bigquery.NewClient(httpClient, *project)
if err != nil {
log.Fatalf("Creating bigquery client: %v", err)
}
if *jobID != "" {
printQueryResults(client, *jobID)
return
}
ds := client.Dataset(*dataset)
var tables []*bigquery.Table
tables, err = ds.ListTables(context.Background())
if err != nil {
log.Fatalf("Listing tables: %v", err)
}
for _, t := range tables {
if tableRE.MatchString(t.TableID) {
printTable(client, t)
}
}
}
开发者ID:nildev,项目名称:account,代码行数:57,代码来源:main.go
示例10: main
func main() {
flag.Parse()
flagsOk := true
if flag.Lookup("project").Value.String() == "" {
fmt.Fprintf(os.Stderr, "Flag --project is required\n")
flagsOk = false
}
var sourceFlagCount int
if flag.Lookup("dataset").Value.String() != "" {
sourceFlagCount++
}
if flag.Lookup("jobid").Value.String() != "" {
sourceFlagCount++
}
if sourceFlagCount != 1 {
fmt.Fprintf(os.Stderr, "Exactly one of --dataset or --jobid must be set\n")
flagsOk = false
}
if !flagsOk {
os.Exit(1)
}
ctx := context.Background()
tableRE, err := regexp.Compile(*table)
if err != nil {
fmt.Fprintf(os.Stderr, "--table is not a valid regular expression: %q\n", *table)
os.Exit(1)
}
client, err := bigquery.NewClient(ctx, *project)
if err != nil {
log.Fatalf("Creating bigquery client: %v", err)
}
if *jobID != "" {
printQueryResults(ctx, client, *jobID)
return
}
ds := client.Dataset(*dataset)
tableIter := ds.Tables(context.Background())
for {
t, err := tableIter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("Listing tables: %v", err)
}
if tableRE.MatchString(t.TableID) {
printTable(ctx, client, t)
}
}
}
开发者ID:trythings,项目名称:trythings,代码行数:56,代码来源:main.go
示例11: UpdateLoggingFlagsFromConfig
func UpdateLoggingFlagsFromConfig(conf *Config) {
err := flag.Lookup("v").Value.Set(strconv.Itoa(conf.Verbosity))
if err != nil {
glog.Errorf("Failed to apply config.Verbosity to flag.v: %v", err)
}
err = flag.Lookup("logtostderr").Value.Set("true")
if err != nil {
glog.Errorf("Failed to set flag.logtostderr to true: %v", err)
}
}
开发者ID:shaunstanislaus,项目名称:fleet,代码行数:11,代码来源:config.go
示例12: logFlush
func logFlush() {
// go run main.go -alsologtostderr -log_dir="./"
logDir := flag.Lookup("log_dir")
testFlag := flag.Lookup("log_dir")
glog.Infoln("lookup before parse", logDir.Name, logDir.Value, testFlag)
err := flag.Set("log_dir", "test_value")
glog.Errorln("err: ", err)
glog.Infoln("abc..")
glog.Infof("abc..%d", 123)
logDir = flag.Lookup("log_dir")
testFlag = flag.Lookup("log_dir")
glog.Infoln("lookup before parse", logDir.Name, logDir.Value, testFlag.Name, testFlag.Value)
glog.Flush()
}
开发者ID:zykzhang,项目名称:practice,代码行数:14,代码来源:main.go
示例13: computeTriple
func computeTriple() string {
if *triple != "" {
// Ensure os/arch aren't specified if triple/ is specified.
//
// This is an ugly way of telling whether or not -os or -arch were
// specified. We can't just check the value, as it will have a default.
archFlag := flag.Lookup("arch")
osFlag := flag.Lookup("os")
flag.Visit(func(f *flag.Flag) {
switch f {
case archFlag, osFlag:
fmt.Fprintln(os.Stderr, tripleArchOsError)
os.Exit(1)
}
})
return *triple
}
// -arch is either an architecture name recognised by
// the gc compiler, or an LLVM architecture name.
targetArch := *arch
if targetArch == "" {
targetArch = runtime.GOARCH
}
switch targetArch {
case "386":
targetArch = "x86"
case "amd64", "x86_64":
targetArch = "x86-64"
}
// -os is either an OS name recognised by the gc
// compiler, or an LLVM OS name.
targetOS := *os_
if targetOS == "" {
targetOS = runtime.GOOS
}
switch targetOS {
case "windows":
targetOS = "win32"
case "darwin":
// Using darwin11 rather than just darwin enables TLS support,
// making llgo-dist run without manually specifying a target
// triple
targetOS = "darwin11"
}
tripleArch := getTripleArchName(targetArch)
return fmt.Sprintf("%s-unknown-%s", tripleArch, targetOS)
}
开发者ID:pcc,项目名称:llgo,代码行数:50,代码来源:llgo.go
示例14: Check
// Check returns a non-nil error if the Config is unusable.
func (c Config) Check() error {
if c.SourceBuffer <= 2 {
return errors.New("-source-buffer must be greater than 2")
}
if c.FrameBytes < 1 {
return errors.New("-frame-bytes must not be zero")
}
if c.Path == "" {
return errors.New("-path must not be empty")
}
if c.CPUMax < 0 {
return errors.New("-cpu-max must not be negative")
}
if c.CPUMax == 0 {
c.CPUMax = runtime.NumCPU()
}
if c.ExecFlag && c.Path != flag.Lookup("path").DefValue && c.Path != "" {
return errors.New("cannot combine -exec and -path")
}
if c.ExecFlag == (len(c.Args) == 0) {
return errors.New("cannot use -exec without providing a command (or vice versa)")
}
if _, ok := Filters[c.FrameFilter]; !ok {
haveFilters := []string{}
for f := range Filters {
haveFilters = append(haveFilters, "\""+f+"\"")
}
return fmt.Errorf("-frame-filter \"%s\" not supported; try one of %v", c.FrameFilter, haveFilters)
}
return nil
}
开发者ID:gitter-badger,项目名称:streamserve,代码行数:32,代码来源:main.go
示例15: init
func init() {
// Override the default cAdvisor housekeeping interval.
if f := flag.Lookup("housekeeping_interval"); f != nil {
f.DefValue = defaultHousekeepingInterval.String()
f.Value.Set(f.DefValue)
}
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:7,代码来源:cadvisor_linux.go
示例16: mustLookup
func mustLookup(flag_name string) *flag.Flag {
val := flag.Lookup(flag_name)
if val == nil {
panic(fmt.Errorf("flag %#v doesn't exist", flag_name))
}
return val
}
开发者ID:spacemonkeygo,项目名称:flagfile,代码行数:7,代码来源:aliases.go
示例17: runDiscoveryServer
func runDiscoveryServer(t *testing.T, serverType taas.ServerType, authType taas.AuthType) *taas.Server {
// TODO: we can avoid setting the port manually when appc/spec gains
// the ability to specify ports for discovery.
// See https://github.com/appc/spec/pull/110
//
// httptest by default uses random ports. We override this via the
// "httptest.serve" flag.
//
// As long as we set the port via the "httptest.serve" flag, we have
// to use https rather than http because httptest.Start() would wait
// forever in "select {}", see
// https://golang.org/src/net/http/httptest/server.go?s=2768:2792#L92
//
// This means this test must:
// - use https only
// - ignore tls errors with --insecure-options=tls
serverURL := flag.Lookup("httptest.serve")
if serverURL == nil {
panic("could not find the httptest.serve flag")
}
serverURL.Value.Set("127.0.0.1:443")
// reset httptest.serve to "" so we don't influence other tests
defer serverURL.Value.Set("")
return runServer(t, serverType, authType)
}
开发者ID:topecz,项目名称:rkt,代码行数:25,代码来源:rkt_tests.go
示例18: GetStartCommand
func GetStartCommand(kubernetesConfig KubernetesConfig) string {
flagVals := make([]string, len(constants.LogFlags))
for _, logFlag := range constants.LogFlags {
if logVal := gflag.Lookup(logFlag); logVal != nil && logVal.Value.String() != logVal.DefValue {
flagVals = append(flagVals, fmt.Sprintf("--%s %s", logFlag, logVal.Value.String()))
}
}
if kubernetesConfig.ContainerRuntime != "" {
flagVals = append(flagVals, "--container-runtime="+kubernetesConfig.ContainerRuntime)
}
if kubernetesConfig.NetworkPlugin != "" {
flagVals = append(flagVals, "--network-plugin="+kubernetesConfig.NetworkPlugin)
}
flags := strings.Join(flagVals, " ")
return fmt.Sprintf(
startCommandFmtStr,
flags,
kubernetesConfig.NodeIP,
constants.RemoteLocalKubeErrPath,
constants.RemoteLocalKubeOutPath,
constants.LocalkubePIDPath,
)
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:27,代码来源:commands.go
示例19: TestMain
func TestMain(m *testing.M) {
flag.Parse()
if flag.Lookup("test.short").Value.String() != "false" {
quickCfg.MaxCount = 10
}
os.Exit(m.Run())
}
开发者ID:escribano,项目名称:syncthing,代码行数:7,代码来源:protocol_test.go
示例20: DEPRECATED_myDpmsControl
// MyDpmsControl detects motion and turns the display screen on or off
// on the external display by using dpms shell commands.
func (m *Viki) DEPRECATED_myDpmsControl(c chan devicemanager.DeviceData) {
log.Printf("starting user routine dpms control...")
res := flag.Lookup("resource").Value.String()
screenOn := false
for {
select {
case got := <-c:
d, _ := got.Data.(string)
_, o := m.getObject(got.Object)
// Got some motion.
if o.checkTag("motion") && d == "On" && !screenOn {
// Turn on screen.
if err := exec.Command(res + "/dpmsoff.sh").Run(); err != nil {
log.Printf("error running dpms off %s ", err)
continue
}
screenOn = true
time.AfterFunc(60*time.Minute, func() {
// Turn off screen.
if err := exec.Command(res + "/dpmson.sh").Run(); err != nil {
log.Printf("error running dpms on %s", err)
return
}
screenOn = false
})
}
}
}
}
开发者ID:deepakkamesh,项目名称:viki,代码行数:33,代码来源:my_dpms_control.go
注:本文中的flag.Lookup函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论