今天我们继续讲解Go语言中命令行,当我们在解析命令行传递的参数时通常会想用最简单的方法来解析自己行用到的命令行参数,那么urfave/cli可以帮助我们快速的解析命令行参数,它是一个简单快速的命令行包,用于在Go语言中构建命令行应用程序,目的是使开发人员能够以表达的方式编写快速分发的命令行应用程序,urfave/cli库抽象出来:FlagCommand,SubCommand等模块,用户只需要设置模块信息,参数的解析和关联就可以,帮助信息自动生成。

在C语言中可以通过getopt(int argc, char * const argv[], const char *optstring)来完成参数解析,这里不做示例,有兴趣的同学可以自己动手尝试一下。

安装urfave/cli:

go get github.com/urfave/cli

包引用方法:

import "github.com/urfave/cli" //引入cli包

urfave/cli包中几个重要的方法:

cli.NewApp() // 创建一个cli实例
Run()       // 程序入口,执行Run后分析参数切片和路由
app.Commands    // 要执行的命令列表
app.Before  // 运行命令之前执行的内容
app.After   // 运行命令之后执行的内容
Subcommands    // 子命令

好,开始我们演示,今天的演示示例有点长,项目目录结构如下:

#tree
.
|-- commands
|   |-- api
|   |   `-- api.go        // api commands
|   `-- service
|       `-- service.go    // 服务 commands
|-- go_cli.go             // main入口
|-- go.mod                // go module管理包
|-- go.sum
`-- webservice|-- bin|   `-- webservice`-- webservice.go     // web服务类

首先,定义webservice类:

webservice类主要完成几个功能:构造函数,释放资源函数,ApiService方法和Service方法。

package webserviceimport "fmt"// web service 类
type WebService struct {Config  stringPort    intLogFile string
}// 返回web service 实例
func NewWebService(config, logFile string, port int) *WebService {var ws = &WebService{Port:    port,Config:  config,LogFile: logFile,}return ws
}// 释放资源
func (ws *WebService) Freed() {}// API调用启动方式
func (ws *WebService) ApiService() {fmt.Println("api service")fmt.Printf("port : %d \n", ws.Port)fmt.Printf("config : %s \n", ws.Config)fmt.Printf("logfile : %s \n", ws.LogFile)// 启动http服务
}// 常驻方式启动
func (ws *WebService) Service() {fmt.Println("service")fmt.Printf("config : %s \n", ws.Config)fmt.Printf("logfile : %s \n", ws.LogFile)// 可以理解成类似Nginx这类服务的启动
}

我们创建Api和Service两个Commands的目录,用于分开执行HTTPService和Service两种模式。

ApiService:

在日常工作中,HTTP-Api是比较常见的获取数据的方式,我们用这个例子来看看在命令行里面如何启动和传递参数的。

package apiimport ("fmt""github.com/gzh/webservice""github.com/urfave/cli""os"
)var Command = cli.Command{Name:    "api",Aliases: []string{"web_api", "webApi"}, // 命令别名Flags: []cli.Flag{// int型参数port,value默认是8080cli.IntFlag{Name:  "port",Value: 8080,Usage: "/usr/local/web_service/service api --port=8080",},// 字符型参数配置文件,默认值为空cli.StringFlag{Name:  "config",Value: "",Usage: "/usr/local/web_service/service api --config=/usr/local/web_service/config",},// 字符型日志文件参数,默认值为空cli.StringFlag{Name:  "log_file",Value: "",Usage: "/usr/local/web_service/service api --log_file=/usr/local/web_service/log/web_service.log",},},Action: func(c *cli.Context) error {var port = c.Int("port")           // 从上下文中获取端口var config = c.String("config")    // 从上下文中获取配置文件var logFile = c.String("log_file") // 从上下文中获取日志文件if config == "" {_, _ = fmt.Fprintf(os.Stderr, "config is empty!\n")os.Exit(100001) // 配置文件错误码}if port <= 0 {_, _ = fmt.Fprintf(os.Stderr, "port is empty!\n")os.Exit(100002) // 端口错误码}if logFile == "" {_, _ = fmt.Fprintf(os.Stderr, "log_file is empty!\n")os.Exit(100003) // 日志文件错误码}// 实例webservice,构造函数参数:config,logfile,portvar api = webservice.NewWebService(config, logFile, port)defer api.Freed()// 启动HTTP-API服务api.ApiService()return nil},
}

Service:

Service类似于Nginx一样,启动后常驻执行的服务,这种在后端中比较多见,下面的示例为Service的启动和传递参数方式。

package serviceimport ("fmt""github.com/gzh/webservice""github.com/urfave/cli""os"
)var Command = cli.Command{Name: "service",Flags: []cli.Flag{// 字符型参数配置,默认值为空cli.StringFlag{Name:  "config",Value: "",Usage: "/usr/local/web_service/service api --config=/usr/local/web_service/config",},// 字符型日志文件参数,默认值为空cli.StringFlag{Name:  "log_file",Value: "",Usage: "/usr/local/web_service/service api --log_file=/usr/local/web_service/log/web_service.log",},},Action: func(c *cli.Context) error {var config = c.String("config")    // 从上下文中获取配置文件var logFile = c.String("log_file") // 从上下文中获取日志文件if config == "" {_, _ = fmt.Fprintf(os.Stderr, "config is empty!\n")os.Exit(100001) // 配置文件错误码}if logFile == "" {_, _ = fmt.Fprintf(os.Stderr, "log_file is empty!\n")os.Exit(100003) // 日志文件错误码}// 实例webservice,构造函数参数:config,logfilevar api = webservice.NewWebService(config, logFile, 0)defer api.Freed()// 启动服务api.Service()return nil},
}

完成上面的几个类之后,我们可以创建go_cli.go文件开始我们的编码。主要是实现main函数,里面创建cli实例,配置参数解析相关信息、版本、描述和帮助等信息。

package mainimport ("fmt""github.com/gzh/commands/api""github.com/gzh/commands/service""github.com/urfave/cli""os"
)func main() {// 实例化命令行app := cli.NewApp()// 服务的名称app.Name = "WebService"// 服务的描述app.Description = "Web服务相关描述"// 服务的用途描述app.Usage = "webservice api --port=8080 --config=path --log_file=/usr/local/webservice/log/go_cli.log"// 服务的版本号信息app.Version = "1.0.0"// 初始化多个命令app.Commands = []cli.Command{// api命令api.Command,// service命令service.Command,}app.Before = func(context *cli.Context) error {// 实现一些逻辑return nil}app.After = func(context *cli.Context) error {// 实现一些逻辑return nil}var err = app.Run(os.Args)if err != nil {fmt.Println("app run fatal! err : ", err)}
}

运行结果:

1、编译运行Api示例:

#go build -o webservice/bin/webservice go_cli.go
#./webservice/bin/webservice api -port=8080 -config=path -log_file=/usr/local/webservice/log/go_cli.log
api service
port : 8080
config : path
logfile : /usr/local/webservice/log/go_cli.log 

2、编译运行Service示例:

#go build -o webservice/bin/webservice go_cli.go
#./webservice/bin/webservice service -config=path -log_file=/usr/local/webservice/log/go_cli.log
service
config : path
logfile : /usr/local/webservice/log/go_cli.log

3、不传递任何参数的时候,会提示命令会出现HELP信息,运行如下。

#go build -o webservice/bin/webservice go_cli.go
#./webservice/bin/webservice
NAME:WebService - webservice api --port=8080 --config=path --log_file=/usr/local/webservice/log/go_cli.logUSAGE:go_cli.exe [global options] command [command options] [arguments...]VERSION:1.0.0DESCRIPTION:Web服务相关描述COMMANDS:apiservicehelp, h  Shows a list of commands or help for one commandGLOBAL OPTIONS:--help, -h     show help--version, -v  print the version

总结:

命令行解析上支持的比较友好,支持的内容比较全面

使用上方便,快速

Go语言 命令行解析(二)相关推荐

  1. Go语言 命令行解析(一)

    命令行启动服务的方式,在后端使用非常广泛,如果有写过C语言的同学相信不难理解这一点!在C语言中,我们可以根据argc和argv来获取和解析命令行的参数,从而通过不同的参数调取不同的方法,同时也可以用U ...

  2. 基于cobra的go语言命令行解析器

    ubuntu安装cobra $ sudo apt install cobra Reading package lists... Done Building dependency tree Readin ...

  3. 一种命令行解析的新思路(Go 语言描述)

    简介: 本文通过打破大家对命令行的固有印象,对命令行的概念解构后重新梳理,开发出一种功能强大但使用极为简单的命令行解析方法.这种方法支持任意多的子命令,支持可选和必选参数,对可选参数可提供默认值,支持 ...

  4. C语言linux getopt_long()函数(命令行解析)(getopt、getopt_long_only)(短选项 -,长选项 --)(option结构体)(optind、optarg变量)

    参考文章:浅谈linux的命令行解析参数之getopt_long函数 文章目录 前言 一.关于命令行参数 二.getopt_long函数 参数以及返回值介绍(以上三个函数都适用): 1.argc和ar ...

  5. C语言自己实现ls -al 功能,支持更换目录。 利用LINUX命令行解析,实现ls,总结船长

    ls -a -l 要读入命令行,就读入-,后面的a和l是体现性质的作用 这个过程用C语言实现是困难的,需要用脚本语言 1.希望实现的功能如下: 流程图: 2. 用到的知识点: man 3 getopt ...

  6. 【嵌入式开发】C语言 命令行参数 函数指针 gdb调试

    . 作者 : 万境绝尘 转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/21551397 | http://www.hanshul ...

  7. .NET:命令行解析器介绍

    背景 经常需要开发一下小工具,之前都是自己解析命令行参数,接触过动态语言社区以后,发现命令行解析有特定的模式和框架可以利用,本文介绍一个 .NET 平台的类库. 示例 需求 拷贝文件,如:CopyFi ...

  8. python getopt argparse_python OptParse模块和argparse命令行解析的用法详解

    https://www.cnblogs.com/wj-1314/p/8974021.html OptParse模块的简单介绍 Python 有两个内建的模块用于处理命令行参数: 一个是 getopt只 ...

  9. python 命令行解析模块_Python命令行解析模块详解

    python2.7 怎么解析命令行输入的中文参数 本文实例讲述了python读取命令行参数的方法.分享给大家供大家参考.具体分析如下: 如果想对python脚本传参数,python中对应的argc, ...

最新文章

  1. Windows Phone 7的启动器和选择器
  2. 【WPF】代码触发Button点击事件
  3. Servlet 简介
  4. linux隐藏tomcat版本_Ubuntu 14.04隐藏Tomcat-7.0.52的版本号与操作系统类型
  5. mysql备份优化_MySQL备份流程及优化
  6. 优酷基于 Pipeline 的播放器开放式架构设计与实践
  7. 搭建集群负载均衡系统
  8. 创建微服务多模块项目
  9. 索鸟快传2.0免费局域网文件共享软件,用C++开发的基于HTTP的文件共享软件,文件下载上传、在线预览
  10. 计算机代数与数论pdf,计算机代数与数论.pdf
  11. find 命令多条件匹配
  12. Sap hana 升级思路
  13. STM32学习笔记(6):PWM控制
  14. 360浏览器网页按钮点击无效
  15. 测试人跳槽~怎么说离职原因新的公司比较能接受?
  16. 添加百度统计,有利于网站SEO,百度终于发声了
  17. 手机端网页监测是否打开键盘
  18. 关于错误:编码GBK的不可映射字符
  19. 不用任何框架,Java 就能实现定时任务的 3 种方法
  20. kafka 解决大消息发送和接收报错问题

热门文章

  1. java多线程的实现方式_Java 多线程(一)——多线程的实现方式
  2. linux怎么切换为oracle用户权限,linux肿么给oracle中用户权限
  3. diy nas配置推荐2019_在Windows Server 2019上配置NAS的方法
  4. html语言中空格用什么表示,HTML中的5种空格各表示的意义
  5. inotifywait监听php,利用inotifywait监控主机文件和目录
  6. 数据分析——朴素贝叶斯原理示意图
  7. mybatis一套完整入门教程
  8. HashMap的7种遍历方式
  9. 算法训练 字符串编辑c语言
  10. SharedPreferences基础