使用眼镜蛇验证标志

下面的草图是使用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())

        }

}


犯罪嫌疑人X
浏览 58回答 1
1回答

一只甜甜圈

假设用户运行如下命令:.“hello”将存储在您分配给标志的变量中,要检查输入是否与任何正则表达式匹配,您可以执行以下操作:cobra-sketch --flag1 "hello"var flag1 stringvar 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    },}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go