The introduction

  • In general, command line tools are useful for a framework, extracting a lot of repetitive work to the command line, executing commands, such as generating models, generating controllers, generating routes, and so on
  • The Go standard library flag is a package for parsing command line arguments
  • However, we chose COBRA to build our command line tools, and many well-known open source projects use the COBRA library to build their command lines, such as Kubernetes, Hugo, ETCD, and many more.
  • Case Code address

Initialize the

1. Install cobra

    goGet github.com/spf13/cobra is usually installed in the bin directory of the gopath directoryCopy the code

2. The initialization

	cobra init --pkg-name=mycmd
Copy the code

It will create a new mycmd directory

▾ mycmd/ ▾ CMD/root.go main.goCopy the code

3. Add an emial subcommand

	cobra add email
Copy the code

2. The characteristics of

1. Basic concepts

  • Command: the operation that needs to be performed;
  • Parameter (Arg) : The parameter of the command, that is, the object to be operated on;
  • Option (Flag) : The command option adjusts the behavior of the command

2. The command

In COBRA, commands and subcommands are represented in the Command structure. Command has a number of fields that can be used to customize the behavior of the Command. In practice, there are only a few that are most commonly used.

  • Use specifies usage information, that is, how the command is invoked. The format is name arg1 [arg2]. The name is the command name, arg1 is mandatory, and arg3 is optional.
  • Short description:
  • Long Long description
  • Run The function that is actually executed
  • Example Use cases

3. The options

Cobra uses Pflag to resolve command-line options. Pflag is the same as flag

  • The global option defines its command and its subcommands can be used

      rootCmd.PersistentFlags().StringVar(&cfgFile, "config", cfgFile, "config file (default is $HOME/.mycmd.toml)")
    Copy the code
  • Local options can only be defined by word commands to be used

	localCmd.Flags().StringVarP(&Source, "source"."s".""."Source directory to read from")
Copy the code

3. Improve the email subcommand


package cmd

import (
	"fmt"
	"log"
	"net/smtp"

	"github.com/jordan-wright/email"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var (
	To  []string
	Cc  []string
	Bcc []string
	/ / theme
	Subject string
	/ / content
	Text string
	// HTML content (preferred)
	HTML string
	// Copy the attachment
	AttachFileName string
	From           string
	Smtp           string
	Port           int
	Password       string
)

// emailCmd represents the email command
var emailCmd = &cobra.Command{
	Use:   "email",
	Short: "Send mail",
	Long:  'In order to send mail more easily',
	Example: 'mycmd email -c' --cc 'yourccemail' --cc 'yourccemail' --cc 'yourccemail' Mycmd email -c "check in" -t "youremail" -- BCC "yourcccemail" Mycmd email -c "check in" -t "youremail" -- HTML =' click ' to send attachment: Mycmd email -c "check in" -t "youremail" --file="./cmd.toml.example" ',
	Run: func(cmd *cobra.Command, args []string) {
		send()
	},
}

func init(a) {
	emailCmd.Flags().StringSliceVarP(&To, "to"."t"And []string{}, "send email to")
	emailCmd.Flags().StringSliceVar(&Cc, "cc"And []string{}, "send email Cc")
	emailCmd.Flags().StringSliceVar(&Bcc, "bcc"And []string{}, "send email Bcc")
	emailCmd.Flags().StringVarP(&Subject, "subject"."s"."Default Theme"."send email Subject")
	emailCmd.Flags().StringVarP(&Text, "context"."c".""."send email Text")
	emailCmd.Flags().StringVar(&HTML, "html".""."send email HTML contect")
	emailCmd.Flags().StringVar(&AttachFileName, "file".""."send email AttachFile")
	emailCmd.MarkFlagRequired("to")
	emailCmd.MarkFlagRequired("context")
	rootCmd.AddCommand(emailCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// emailCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// emailCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func send(a) {
	From = viper.GetString("email.from")
	Smtp = viper.GetString("email.smtp")
	Port = viper.GetInt("email.port")
	Password = viper.GetString("email.password")

	e := email.NewEmail()
	e.From = From
	e.To = To
	e.Cc = Cc
	e.Bcc = Bcc
	e.Subject = Subject
	e.AttachFile(AttachFileName)
	ifHTML ! ="" {
		e.HTML = []byte(HTML)
	} else {
		e.Text = []byte(Text)
	}
	auth := smtp.PlainAuth("", From, Password, Smtp)
	addr := fmt.Sprintf("%s:%d", Smtp, Port)
	err := e.Send(addr, auth)
	iferr ! =nil {
		log.Fatal("email ", err)
	}

	log.Println("Sent successfully")}Copy the code

4. Test commands

  1, compilergo build .
  2Run./mycmd email -c as shown in the example"Content" -t "[email protected]"
Copy the code

5, other

  • The validation option is required: use MarkFlagRequired

Cobra also provides rich features and customizable interfaces, such as setting hook functions to perform certain operations before and after command execution; Make documents in Markdown/ReStructed Text/Man Page, etc., for those who need them

6, reference

  1. Go One pool of COBRA daily
  2. email

7. Series of articles

  • Serial set up a Golang environment
  • Serial 2 Install Gin
  • Serial three defines the directory structure
  • Serial four build case API1
  • Serial five build case API2
  • Serialized six access Swagger interface documents
  • Serialize seven log components
  • Serial eight graceful restart and stop
  • Serialize the external Makefile build
  • Serialize other Cron scheduled tasks
  • Serialized content to create command-line tools
  • 3 days to build exclusive Cache(First day)
  • 3 days to build exclusive Cache(Second day)
  • Third Day: Creating a dedicated Cache