duanke1984 2018-11-25 13:58
浏览 40
已采纳

如何让每个眼镜蛇命令解析自己的标志? 获取初始化循环(预期,但是如何避免?)

I'm following the guide on https://github.com/spf13/cobra#flags, but I'm confused by some of the content there.

I have a few services (rest api, email service, events) and I'm trying to do something like this:

go run *.go rest -env DEV -p 3000

go run *.go events -env DEV -p 3001

I'm following the github page, so I have defined my rootCmd and restCmd as such:

var rootCmd = &cobra.Command{
    Use: "myappname",
}

var restCmd = &cobra.Command{
    Use:   "rest",
    Short: "REST API",
    Long:  "REST API",
    Run:   runRest,
}

And in the runRest method, should I be doing something like

var env string
restCmd.Flags().StringVarP(&env, "env", "env", "", "environment")

Please let me know.

Thanks

  • 写回答

1条回答 默认 最新

  • doubaisui2526 2018-11-25 15:59
    关注

    Each sub command can have their own flags. You can do this as following:

    package main
    
    import (
        "fmt"
        "log"
    
        "github.com/spf13/cobra"
    )
    
    var rootCmd = &cobra.Command{
        Use: "app",
    }
    
    func NewCmdRest() *cobra.Command {
        var env string
        var restCmd = &cobra.Command{
            Use: "rest",
            Run: func(cmd *cobra.Command, args []string) {
                fmt.Println("rest:", env)
            },
        }
    
        restCmd.Flags().StringVarP(&env, "env", "e", "", "environment")
        return restCmd
    }
    
    func NewCmdEvent() *cobra.Command {
        var env string
        var eventCmd = &cobra.Command{
            Use: "event",
            Run: func(cmd *cobra.Command, args []string) {
                fmt.Println("event:", env)
            },
        }
    
        eventCmd.Flags().StringVarP(&env, "env", "e", "", "environment")
        return eventCmd
    }
    
    func init() {
        rootCmd.AddCommand(NewCmdRest())
        rootCmd.AddCommand(NewCmdEvent())
    }
    
    func main() {
        if err := rootCmd.Execute(); err != nil {
            log.Fatal(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用