duanlidi1051 2017-01-11 19:32
浏览 27

我可以添加带有Go标志的命令吗?

I know I can define flags like this:

initPtr := flag.String("init", "config.json", "Initialize with config filename")

Which I will call like this:

myapp --init=myconfig.json

I wonder though if I can define something like commands so that to call the app like this?

myapp init --filename=myconfig.json
myapp check --filename=myconfig.json
myapp run
  • 写回答

2条回答 默认 最新

  • dongwuwan5646 2017-01-11 19:45
    关注

    Yes, you can.

    Take a look at https://golang.org/pkg/flag/ for FlagSet documentation.

    And for a working example: https://github.com/constabulary/gb/blob/master/cmd/gb/main.go

    And an example as requested by miltonb:

    % go run flagset.go init --filename=foo.json foo bar
    init foo.json [foo bar]
    % go run flagset.go check --filename=bar.json 1 2 3
    check bar.json [1 2 3]
    % go run flagset.go run
    run
    % cat flagset.go
    package main
    
    import (
        "flag"
        "fmt"
        "os"
    )
    
    func main() {
        init := flag.NewFlagSet("init", flag.ExitOnError)
        initFile := init.String("filename", "myconfig.json", "configuration file")
    
        check := flag.NewFlagSet("check", flag.ExitOnError)
        checkFile := check.String("filename", "myconfig.json", "configuration file")
    
        if len(os.Args) <= 1 {
            flag.Usage()
            os.Exit(1)
        }
    
        switch os.Args[1] {
        case "init":
            if err := init.Parse(os.Args[2:]); err == nil {
                fmt.Println("init", *initFile, init.Args())
            }
        case "check":
            if err := check.Parse(os.Args[2:]); err == nil {
                fmt.Println("check", *checkFile, check.Args())
            }
        case "run":
            fmt.Println("run")
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line