登录
首页 >  Golang >  Go问答

使用 Cobra 进行标志验证

来源:stackoverflow

时间:2024-02-11 22:42:13 472浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《使用 Cobra 进行标志验证》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

下面的草图是使用 cobra 和 go 编写的命令行应用程序。如果 flag1 的值与正则表达式 ^\s+\/\s+ 不匹配,我想抛出错误。我该怎么做?

package cmd

import (
        "fmt"
        "os"
        "github.com/spf13/cobra"

        homedir "github.com/mitchellh/go-homedir"
        "github.com/spf13/viper"
)

var flag1 string
var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
        Use:   "cobra-sketch",
        Short: "Sketch for Cobra flags",
  Long: "Sketch for Cobra flags",
        Run: func(cmd *cobra.Command, args []string) { fmt.Printf("Flag1 is %s\n", flag1)},
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
        cobra.CheckErr(rootCmd.Execute())
}

func init() {
        cobra.OnInitialize(initConfig)
 
        rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra-sketch.yaml)")
  rootCmd.PersistentFlags().StringVar(&flag1, "flag1", "", "Value of Flag 1")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
        if cfgFile != "" {
                // Use config file from the flag.
                viper.SetConfigFile(cfgFile)
        } else {
                // Find home directory.
                home, err := homedir.Dir()
                cobra.CheckErr(err)

                // Search config in home directory with name ".cobra-sketch" (without extension).
                viper.AddConfigPath(home)
                viper.SetConfigName(".cobra-sketch")
        }

        viper.AutomaticEnv() // read in environment variables that match

        // If a config file is found, read it in.
        if err := viper.ReadInConfig(); err == nil {
                fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
        }
}

正确答案


假设用户运行如下命令:cobra-sketch --flag1“hello”。 “hello”将存储在您分配给该标志的 var flag1 string 变量中,要检查输入是否与任何正则表达式匹配,您可以执行以下操作:

var rootCmd = &cobra.Command{
    Use:   "cobra-sketch",
        ...
    RunE: func(cmd *cobra.Command, args []string) error {
        // You can also use MustCompile if you are sure the regular expression 
        // is valid, it panics instead of returning an error
        re, err := regexp.Compile(`^\s+\/\s+`)
        if err != nil {
            return err // Handle error
        }

        if !regexp.MatchString(flag1) {
            return fmt.Errorf("invalid value: %q", flag1)
        }

        fmt.Printf("Flag1 is %s\n", flag1)
        return nil
    },
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>