Golang Advanced (ii)--COBRA more practical command line

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

+++
Title= "Golang Advanced (ii)--COBRA more practical command line"
Date= "2017-10-11"
tags=["Golang", "Glide", "Docker"]
categories=["Resource Management"]
Description= "Golang itself with the command-line package, a variety of case, a code neat people looking at the big head"
+++

Cobra is a very good command-line package, and Docker,hugo are using

Base command

First create a base command

package cmdimport (    "github.com/spf13/cobra")var RootCmd = &cobra.Command{    "gonne",    func(cmd *cobra.Command, args []string) {        println("gonne is my ai friend")    },}

Using commands

Invoke the command in the main method, yes, it's that simple.

package mainimport (    "fmt"    "os"    "lastsweetop.com/cmd")func main() {    ifnil {        fmt.Println(err)        os.Exit(1)    }}

At the command-line input gonne , the methods in the base command are executed Run

appletekiMacBook-Pro:src apple$ gonnegonne is my ai friend

Sub-command

Adding subcommands to the base command is also fairly straightforward, eliminating the need to write any code in the base command and the main method, just create a new go file, and the multiple subcommands are independent of each other, how elegant the code is, and say goodbye to the various case

package cmdimport"github.com/spf13/cobra"func init() {    RootCmd.AddCommand(versionCmd)}var versionCmd = &cobra.Command{    Use:   "version",    "Print the version number of Gonne",    func(cmd *cobra.Command, args []string) {        println("gonne version is 0.0.1")    },}

The effect is as follows:

0.0.1

Other

There is also a question about the parameters, we next and how to do a background process together to speak

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.