当前位置:网站首页>Build go command line program tool chain
Build go command line program tool chain
2022-06-24 15:53:00 【fifteen billion two hundred and thirty-one million one hundred 】
The story of laziness
Today's recommendation needs to start with a lazy story :
Words , Not long ago , You need to output a cool... Sorted by release time Go List of recommended historical articles , Something like this

So , from GoCN The last one copy The title of the article ,5 Chapter down , Hands and eyes are out of tune , At this moment, I remembered that I seemed to be a yard farmer , This situation and this scene must coding a section , Let the code output this list .
The idea is simple , to glance at GoCN List of articles API, Let's look at the authentication method ( see header It's through cookie), Then you can coding 了 , adopt API Pull article data , Extract the required fields and assemble them into MD The output is finished ! When preparing a main.go When it's done , In line with the right coding The awe of , Simply think about the readability of the program 、 Expansibility , Decide whether to build a relatively complete command line program , as follows :

Protagonist on stage
Then you need to implement the command line prompt in the above figure , Program parameter analysis, etc , Of course, it can be achieved without the help of third-party packages . but , Why don't the trees planted by our predecessors enjoy the cool , In the industry, there are mature implementations for the development of command line tools , Here is the main character of this article :
cobra: Apply command line framework pflag: Command line parameter parsing viper: Profile parsing
Let's take a look at how to use these three big brothers to build Go Command line program .
Let's take a brief look at the project structure :
.
├── cmd
│ ├── pull.go
│ └── root.go
├── config.yaml
├── file
│ └── cool-go.md
├── go.mod
├── go.sum
├── gocn-cli
└── main.go
Then introduce the three libraries recommended above :
go get -u github.com/spf13/[email protected]
go get -u github.com/spf13/viper
go get -u github.com/spf13/pflag
Coding
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
)
var (
cfgFile string
)
func init() {
cobra.OnInitialize(initConfig)
// Parsing configuration file parameters
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is ./config.yaml)")
}
// initConfig viper Load profile
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
viper.AddConfigPath(".")
viper.SetConfigName("config")
}
if err := viper.ReadInConfig(); err != nil {
fmt.Println("Can't read config file:", err)
os.Exit(1)
}
}
// Create a global rootCmd
var rootCmd = &cobra.Command{
Use: "gocn-cli",
Short: "gocn-cli is a command line tool for gocn.com",
Long: "gocn-cli is a command line tool for gocn.com",
Run: func(cmd *cobra.Command, args []string) {
},
}
// Execute Carry out orders main call
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
package cmd
import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
)
var (
moduleName string
)
func init() {
// to rootCmd Add new orders pullCmd
rootCmd.AddCommand(pullCmd)
pullCmd.Flags().StringVarP(&moduleName, "module", "m", "", "module name")
}
var pullCmd = &cobra.Command{
Use: "pull gocn data",
Short: "pull gocn data",
Run: func(cmd *cobra.Command, args []string) {
pullHandler()
},
}
// pullHandler pullCmd Corresponding processing function
func pullHandler() {
if moduleName == "" {
fmt.Println("module name is required")
os.Exit(1)
}
switch moduleName {
case "cool-go":
pullCoolGo()
default:
fmt.Println("module name is invalid")
os.Exit(1)
}
}
func pullCoolGo() {
// TODO Write Your Code
}
Conclusion
The above briefly introduces how to use cobra、viper、pflag, Of course, there are many other uses for them , Here is a simple introduction .
so , A good command line program can be built through simple code .
Reference resources
https://github.com/spf13/cobra
https://github.com/spf13/viper
https://github.com/spf13/pflag

边栏推荐
猜你喜欢

nifi从入门到实战(保姆级教程)——环境篇

Database tools in intelij can connect but cannot display schema, tables

Using alicloud RDS for SQL Server Performance insight to optimize database load - first understanding of performance insight

日志记录真没你想的那么简单

我与“Apifox”的网络情缘

微信公众号调试与Natapp环境搭建

推荐几款超级实用的数据分析利器

为什么企业实施WMS仓储管理系统很容易失败

The equipment is connected to the easycvr platform through the national standard gb28181. How to solve the problem of disconnection?

使用阿里云RDS for SQL Server性能洞察优化数据库负载-初识性能洞察
随机推荐
Istio practical tips: Customize Max_ body_ size
CAP:多重注意力机制,有趣的细粒度分类方案 | AAAI 2021
Why is it easy for enterprises to fail in implementing WMS warehouse management system
How to implement SQLSERVER database migration in container
Hardware security threats of cloud infrastructure
Decomposition of Uber dependency injection into dig source code analysis
Using alicloud RDS for SQL Server Performance insight to optimize database load - first understanding of performance insight
中国产品经理的没落:从怀恋乔布斯开始谈起
Mysql之Binlog
Linux record -4.22 MySQL 5.37 installation (supplementary)
Remember: never use UTF-8 in MySQL
How to use nested tags in thymeleaf3 Tags
【Prometheus】6. Prometheus and kubernetes (incomplete)
Golang+redis distributed mutex
The first in China! Tencent cloud key management system passes password application verification test
Binary computing
Special topic of IM code scanning login Technology (III): easy to understand. A detailed principle of IM code scanning login function is enough
Logging is not as simple as you think
MySQL 开发规范
几种常见的DoS攻击