[go] go language practice – go-fly online customer service Cobra library command line parameter analysis

Time:2021-9-12

The first way to parse command line parameters is to use the flag package in the standard library. Later, it is more complex and difficult to add new parameters, so it is easier to use Cobra

For example, executing go fly server port 8081 is a running project

Execute go fly install to import the database

 

Directory structure:

 

 

Add the CMD directory as the CMD package, and directly define global variables and exportable functions in the code. This is the case in root.go

package cmd
import (
    "errors"
    "fmt"
    "github.com/spf13/cobra"
    "os"
)
var rootCmd = &cobra.Command{
    Use:   "go-fly",
    Short: "go-fly",
    Long: ` simple and fast go language web online customer service 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 ("at least one parameter is required!")
    }
    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)
}

 

Call the excete method directly in the entry file for use

package main

import (
    "github.com/taoshihan1991/imaptool/cmd"
)

func main() {
    cmd.Execute()
}

AddCommand adds parameters, such as the instance of versioncmd, which is defined in version.go, and prints the version number when executing 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)
    },
}

Direct access effect:

 

 

Add parameter effect:

 

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]