当前位置:网站首页>Golang language cli Library
Golang language cli Library
2022-07-22 15:32:00 【Saggitarxm】
Many uses Go Written command-line programs are used urfave/cli This library , Include geth, It is necessary to briefly understand .
use C Anyone who has written a command-line program should be familiar , We need to argc/argv Parse the command line parameters one by one , Call different functions , Finally, I have to write a usage() Function to print help information .urfave/cli Encapsulate this process , Abstract out flag/command/subcommand These modules , Users only need to provide some module configurations , The parsing and correlation of parameters are completed inside the Library , Help information can also be generated automatically .
for instance , We want to implement the following command line program :
NAME:
GoTest - hello world
USAGE:
GoTest [global options] command [command options] [arguments...]
VERSION:
1.2.3
COMMANDS:
help, h Shows a list of commands or help for one command
arithmetic:
add, a calc 1+1
sub, s calc 5-3
database:
db database operations
GLOBAL OPTIONS:
--lang FILE, -l FILE read from FILE (default: "english")
--port value, -p value listening port (default: 8000)
--help, -h Help!Help!
--print-version, -v print version
1. The basic structure
After importing the package , adopt cli.NewApp() Create an instance , And then call Run() Method implements a basic command line program .
Of course , In order to let our program do something , You can specify the entry function app.Action, The specific writing method is as follows :
import (
"fmt"
"gopkg.in/urfave/cli.v1"
)
func main() {
app := cli.NewApp()
app.Action = func(c *cli.Context) error {
fmt.Println("BOOM!")
return nil
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
2. Common configuration
It is the basic information that needs to be displayed in the help :
app.Name = "GoTest"
app.Usage = "hello world"
app.Version = "1.2.3"
3. Flag To configure
The details correspond to the following information in the help :
--lang FILE, -l FILE read from FILE (default: "english")
--port value, -p value listening port (default: 8000)
The corresponding code :
var language string
app.Flags = []cli.Flag {
cli.IntFlag {
Name: "port, p",
Value: 8000,
Usage: "listening port",
},
cli.StringFlag {
Name: "lang, l",
Value: "english",
Usage: "read from `FILE`",
Destination: &language,
},
}
You can see , every last flag They all correspond to one cli.Flag An instance of an interface .
Name The character after the comma in the field indicates flag Abbreviation , in other words "--port" and "-p" It is equivalent. .
Value Field can specify flag The default value of .
Usage The fields are flag Description information of .
Destination The field can be this flag Specify a recipient , Like the one above language Variable . The analysis is finished "--lang" This flag It will be automatically stored in this variable , The following code can directly use the value of this variable .
in addition , If you want to give users some hints about attribute value types , You can go through placeholders (placeholder) To achieve , Like the one above "--lang FILE". Placeholders pass `` Sign to mark .
We can do it in app.Action Test and print these flag Value :
app.Action = func(c *cli.Context) error {
fmt.Println("BOOM!")
fmt.Println(c.String("lang"), c.Int("port"))
fmt.Println(language)
return nil
}
in addition , Normally speaking, in the help message flag It is arranged according to the declaration order in the code , If you want them to be arranged in dictionary order , With the aid of sort:
import "sort"
sort.Sort(cli.FlagsByName(app.Flags))
Last ,help and version these two items. flag There is a default implementation , You can also change it yourself :
cli.HelpFlag = cli.BoolFlag {
Name: "help, h",
Usage: "Help!Help!",
}
cli.VersionFlag = cli.BoolFlag {
Name: "print-version, v",
Usage: "print version",
}
4. Command To configure
The command-line program has flag, also command( such as git log, git commit wait ).
And each of them command There may be subcommand, You must add two command line parameters to complete the corresponding operation . Like our db The command contains 2 Sub orders , If input GoTest db -h The following message will be displayed :
NAME:
GoTest db - database operations
USAGE:
GoTest db command [command options] [arguments...]
COMMANDS:
insert insert data
delete delete data
OPTIONS:
--help, -h Help!Help!
Every command All correspond to a cli.Command An instance of an interface , The entry function passes Action Appoint . If you want to realize group display in help information , Can be for each command To specify a Category. The specific code is as follows :
app.Commands = []cli.Command {
{
Name: "add",
Aliases: []string{"a"},
Usage: "calc 1+1",
Category: "arithmetic",
Action: func(c *cli.Context) error {
fmt.Println("1 + 1 = ", 1 + 1)
return nil
},
},
{
Name: "sub",
Aliases: []string{"s"},
Usage: "calc 5-3",
Category: "arithmetic",
Action: func(c *cli.Context) error {
fmt.Println("5 - 3 = ", 5 - 3)
return nil
},
},
{
Name: "db",
Usage: "database operations",
Category: "database",
Subcommands: []cli.Command {
{
Name: "insert",
Usage: "insert data",
Action: func(c *cli.Context) error {
fmt.Println("insert subcommand")
return nil
},
},
{
Name: "delete",
Usage: "delete data",
Action: func(c *cli.Context) error {
fmt.Println("delete subcommand")
return nil
},
},
},
},
}
If you want to command Before and after execution, complete some operations after execution , You can specify app.Before/app.After These two fields :
app.Before = func(c *cli.Context) error {
fmt.Println("app Before")
return nil
}
app.After = func(c *cli.Context) error {
fmt.Println("app After")
return nil
}
Test specifically :
$ GoTest add
$ GoTest db insert
5. Summary
On the whole ,urfave/cli This library is still very easy to use , It's done a lot routine The job of , Programmers only need to focus on the implementation of specific business logic .
Complete with demo Code :
package cli
import (
"fmt"
"os"
"log"
"sort"
"gopkg.in/urfave/cli.v1"
)
func Run() {
var language string
app := cli.NewApp()
app.Name = "GoTest"
app.Usage = "hello world"
app.Version = "1.2.3"
app.Flags = []cli.Flag {
cli.IntFlag {
Name: "port, p",
Value: 8000,
Usage: "listening port",
},
cli.StringFlag {
Name: "lang, l",
Value: "english",
Usage: "read from `FILE`",
Destination: &language,
},
}
app.Commands = []cli.Command {
{
Name: "add",
Aliases: []string{"a"},
Usage: "calc 1+1",
Category: "arithmetic",
Action: func(c *cli.Context) error {
fmt.Println("1 + 1 = ", 1 + 1)
return nil
},
},
{
Name: "sub",
Aliases: []string{"s"},
Usage: "calc 5-3",
Category: "arithmetic",
Action: func(c *cli.Context) error {
fmt.Println("5 - 3 = ", 5 - 3)
return nil
},
},
{
Name: "db",
Usage: "database operations",
Category: "database",
Subcommands: []cli.Command {
{
Name: "insert",
Usage: "insert data",
Action: func(c *cli.Context) error {
fmt.Println("insert subcommand")
return nil
},
},
{
Name: "delete",
Usage: "delete data",
Action: func(c *cli.Context) error {
fmt.Println("delete subcommand")
return nil
},
},
},
},
}
app.Action = func(c *cli.Context) error {
fmt.Println("BOOM!")
fmt.Println(c.String("lang"), c.Int("port"))
fmt.Println(language)
// if c.Int("port") == 8000 {
// return cli.NewExitError("invalid port", 88)
// }
return nil
}
app.Before = func(c *cli.Context) error {
fmt.Println("app Before")
return nil
}
app.After = func(c *cli.Context) error {
fmt.Println("app After")
return nil
}
sort.Sort(cli.FlagsByName(app.Flags))
cli.HelpFlag = cli.BoolFlag {
Name: "help, h",
Usage: "Help!Help!",
}
cli.VersionFlag = cli.BoolFlag {
Name: "print-version, v",
Usage: "print version",
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
More articles are welcome “ Xinxin lights the lamp ” special column :https://blog.csdn.net/turkeycock/article/category/7669858
边栏推荐
- 产业数字化全面加速,智能云网2.0重新定义数字化转型
- JMeter notes 1 | introduction and architecture of JMeter
- Graffiti Wi Fi & ble SoC development slide strip (5) -- burning authorization
- Distributed link tracking skywalking practice
- How Linux queries Oracle error logs
- golang语言cli库
- [C language - program compilation] how does the line by line code get to an executable program step by step?
- 海康、大华、宇视拉实时流url规则总结
- 【C语言-程序编译】一行行代码究竟是怎么一步步到可执行程序的?
- 机器学习笔记 - 机器学习系统设计流程概述
猜你喜欢
【06】指令跳转:原来if...else就是goto
For more than 20 years, how has classified protection "kept pace with the times"?
LeetCode 0814. 二叉树剪枝
产品Banner样式类型分析
什么是探索性测试?探索性测试有哪些方法?
如何正确使用电流探头
Tdengine learning notes
【07】函数调用:为什么会发生stack overflow?
Visual studio pit record
Succès de la construction du cluster expérimental tdengine
随机推荐
MySQL練習一數據庫的知識
TDengine实验集群搭建 Success
Record online double write failure log MySQL error troubleshooting reasons
MySQL(28)——事务相关
Machine learning notes - overview of machine learning system design process
【C语言-程序编译】一行行代码究竟是怎么一步步到可执行程序的?
pyside2做个简易的浏览器
PLT draw and save the results
How to align MathType formula and word text layout
92. (leaflet chapter) leaflet situation plotting - acquisition of attack direction
Clickhouse related SQL summary: create table, partition / primary key / sorting settings, delete table, delete partition, modify table fields
Rebound shell carries out suid authorization through ordinary users
DM8:查询达梦数据库数据文件使用大小限制
Cloud native
Distributed link tracking skywalking practice
Write a maze game with R
df.describe() 详解+用法+示例
ADB common commands
adb常见命令
MySQL写循环语句的方法