zoukankan      html  css  js  c++  java
  • [Go]GO语言实战-GO-FLY在线客服cobra库命令行参数解析

    最开始的解析命令行参数是使用的标准库里面的flag包,后来想增加新的参数的时候比较复杂和困难,因此使用cobra更加简单一些

    比如执行go-fly server port 8081是运行项目

    执行go-fly install是导入数据库

    目录结构:

    增加cmd目录,作为cmd包,代码中直接定义全局变量和可导出的函数 , root.go里面是这样的

    package cmd
    import (
        "errors"
        "fmt"
        "github.com/spf13/cobra"
        "os"
    )
    var rootCmd = &cobra.Command{
        Use:   "go-fly",
        Short: "go-fly",
        Long: `简洁快速的GO语言WEB在线客服 https://gofly.sopans.com`,
        Args:args,
        Run: func(cmd *cobra.Command, args []string) {
    
        },
    }
    func args(cmd *cobra.Command, args []string) error{
        if len(args)<1{
    
            return errors.New("至少需要一个参数!")
        }
        return nil
    }
    func Execute() {
        if err := rootCmd.Execute(); err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
    }
    func init() {
        rootCmd.AddCommand(versionCmd)
        rootCmd.AddCommand(serverCmd)
        rootCmd.AddCommand(installCmd)
    }

    在入口文件中直接调用Excute方法进行使用

    package main
    
    import (
        "github.com/taoshihan1991/imaptool/cmd"
    )
    
    func main() {
        cmd.Execute()
    }

    AddCommand就是在增加参数,比如versionCmd这个实例,定义在了version.go里面 ,执行go-fly version的时候打印版本号

    package cmd
    
    import (
        "fmt"
        "github.com/spf13/cobra"
        "github.com/taoshihan1991/imaptool/config"
    )
    
    var versionCmd = &cobra.Command{
        Use:   "version",
        Short: "example:go-fly version",
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("go-fly "+config.Version)
        },
    }

    直接访问效果:

    加上参数效果:

  • 相关阅读:
    error:Unterminated &lt;form:form tag
    error:org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    mvc-dispatchar-servlet.xml文件报错
    修改MySQL密码
    Injection of autowired dependencies failed
    IDEA jsp模板
    jstl的表达式不能解析
    前端学习的小窍门
    Git的使用
    MySql数据库表的查询操作
  • 原文地址:https://www.cnblogs.com/taoshihan/p/13635847.html
Copyright © 2011-2022 走看看