duanqujing3863 2014-08-04 07:03
浏览 23
已采纳

golang标志在第一个非选项后停止解析

i am building a little cli tool that boots my app in development or production.

the way i want it to work is like this:

app run --dev or app run --prod

Atm it doest parses the flags after my command but only before my command. So this works

app --dev run or app --prod run

Any idee how to fix it this so i can use it after my command? here is my code

func main() {
    //flag.Usage := usage
    flag.Parse()
    args := flag.Args()
    if len(args) == 0 {
        Usage()
        os.Exit(0)
    }

    if *dev {
        os.Setenv("ENV", "development")
    }

    if *prod {
        os.Setenv("ENV", "production")
    }

    switch {
    // Run
    case args[0] == "run" && len(args) == 1:
        os.Setenv("port", *port)
        log.Printf("Booting in %s", os.Getenv("ENV"))
        Run()

    // Help
    case args[0] == "help" && len(args) == 1:
        Usage()
    }
}
  • 写回答

2条回答 默认 最新

  • dongxian7489 2014-08-04 07:15
    关注

    Traditionally, the UNIX option parser getopt() stops parsing after the first non-option. The glibc altered this behavior to support options in arbitrary positions, a controversial decision. The flag package implements the traditional behavior.

    One thing you could do is permuting the arguments array before parsing the flags. That's what the glibc does:

    func permutateArgs(args []string) int {
        args = args[1:]
        optind := 0
    
        for i := range args {
            if args[i][0] == '-' {
                tmp := args[i]
                args[i] = args[optind]
                args[optind] = tmp
                optind++
            }
        }
    
        return optind + 1
    }
    

    This code permutates args such that options are in front, leaving the program name untouched. permutateArgs returns the index of the first non-option after permutation. Use this code like this:

    optind := permutateArgs(os.Args)
    flags.Parse()
    
    // process non-options
    for i := range os.Args[optind:] {
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 设计一个温度闭环控制系统
  • ¥100 关于加载卡的问题有能知道这个要怎么处理吗?
  • ¥100 rtmpose姿态评估
  • ¥15 java 通过反射找路径下的类,打包后就找不到
  • ¥15 通联支付网上收银统一下单接口
  • ¥15 angular有偿编写,
  • ¥15 centos7系统下abinit安装时make出错
  • ¥15 hbuildex运行微信小程序报错
  • ¥15 关于#python#的问题:我知道这个问题对你们来说肯定so easy
  • ¥15 wpf datagrid如何实现多层表头