golang之命令行工具Cobra

发布时间 2023-09-28 14:52:51作者: X-Wolf

github地址: https://github.com/spf13/cobra

 

[安装]

go get -u github.com/spf13/cobra@latest

使用cobra_cli工具

go install github.com/spf13/cobra-cli@latest

 

[使用]

# 初始化工程
cobra-cli init


# 添加应用
cobra-cli add timezone

  

 

示例:

// timezone.go
/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
    "fmt"
    "time"

    "github.com/spf13/cobra"
)

// timezoneCmd represents the timezone command
var timezoneCmd = &cobra.Command{
    Use:   "timezone",
    Short: "Get the current time in a given timezone",
    Long: `Get the current time in a given timezone.
        This command takes one argument, the timezone you want to get the current time,
        It returns the current time in datetime format.
    `,
    Args: cobra.ExactArgs(1), // 需要一个额外参数
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Println("timezone called")
        timezone := args[0]
        //currentTime, err := getTimeInTimezone(timezone)
        //if err != nil {
        //    log.Fatalln("The timezone string is invalid")
        //}
        //fmt.Println(currentTime)
        //
        location, _ := time.LoadLocation(timezone)
        currentTime := time.Now().In(location)
        dateFlag, _ := cmd.Flags().GetString("date")
        var date string
        if dateFlag != "" {
            date = currentTime.Format(dateFlag)
        } else {
            date = currentTime.Format(time.RFC1123)
        }
        fmt.Printf("current timezone:%v , time:%v\n", timezone, date)
    },
}

func init() {
    rootCmd.AddCommand(timezoneCmd)

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

    // Cobra supports Persistent Flags which will work for this command
    // and all subcommands, e.g.:
    timezoneCmd.PersistentFlags().String("date", "", "returns the date in a time zone in a specialfied format")

    // Cobra supports local flags which will only run when this command
    // is called directly, e.g.:
    //timezoneCmd.Flags().String("date", "", "Date for which to get the time (format: yyyy-mm-dd)")
}

 

 

 

参考:

  • https://www.digitalocean.com/community/tutorials/how-to-use-the-cobra-package-in-go