第一章 常用库 v1.0
第一部分 命令行框架(Cobra)
一、简介
Cobra 是一个用于 Go 语言的命令行接口(CLI)库,广泛用于构建强大且灵活的命令行工具。
其主要特点如下:
- 简单易用:Cobra 提供了简单的 API,使得开发者可以快速创建命令行工具。
- 自动生成帮助文档:Cobra 可以自动生成帮助文档和使用说明,减少了开发者的工作量。
- 支持子命令:Cobra 支持嵌套的子命令,使得命令行工具可以更加模块化和组织化。
- 灵活的标志(Flags)处理:Cobra 提供了强大的标志处理功能,可以轻松解析命令行参数。
- 集成 Viper:Cobra 可以与 Viper 集成,方便进行配置管理。
安装命令:
bash
go get -u github.com/spf13/cobra
二、使用
go
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var rootCmd = &cobra.Command{
Use: "app",
Short: "This is a simple CLI application",
Run: func(cmd *cobra.Command, args []string) { // 执行命令调用函数
fmt.Println("Hello, Cobra!")
},
}
rootCmd.Execute()
}
go
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var rootCmd = &cobra.Command{Use: "app"}
var echoCmd = &cobra.Command{
Use: "echo [message]",
Short: "Echo prints the input message",
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(args[0])
},
}
rootCmd.AddCommand(echoCmd)
rootCmd.Execute()
}
三、标志
Cobra提供多种类型标志,包括字符串、整数、布尔值等。
go
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func main() {
var name string
var rootCmd = &cobra.Command{
Use: "app",
Short: "This is a simple CLI application",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Hello, %s!\n", name)
},
}
rootCmd.Flags().StringVarP(&name, "name", "n", "World", "name to greet")
rootCmd.Execute()
}
四、集成Viper
Viper是一个用于Go应用的配置管理包,Cobra可以与其无缝集成
示例
go
package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
func main() {
var rootCmd = &cobra.Command{
Use: "app",
Short: "This is a simple CLI application",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Config file used:", viper.ConfigFileUsed())
},
}
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is ./config.yaml)")
rootCmd.Execute()
}
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
}
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err != nil {
fmt.Printf("Read config file: %s fail...\n", viper.ConfigFileUsed())
}
fmt.Println("Using config file:", viper.ConfigFileUsed())
}