Table of Contents
摘要
入门介绍
一个简易的http服务器
Hello, this is my http server!
标签cli,usage,dft
创建命令行程序的命令行工具 clier goplus
Home Web Front-end HTML Tutorial 使用go构建命令行程序的快捷之道_html/css_WEB-ITnose

使用go构建命令行程序的快捷之道_html/css_WEB-ITnose

Jun 24, 2016 am 11:18 AM

摘要

本文介绍用于构建命令行程序的开源工具 mkideal/cli 。golang标准库 flag 是官方自带的用于命令行参数解析的实用库,而本文介绍的 cli 的主要功能基本与 flag 库相同,但是提供相对简洁友好的用法以及更多实用工具。 cli 的主要特性包括:

  • 基于golang的tag和反射实现。
  • 参数类型和范围检查,以及自定义的验证函数。
  • 支持短格式和长格式的flag像 -h 和 --help 。
  • 支持指定默认值,甚至是以环境变量为默认值。
  • 支持数组和map为参数。
  • 友好的帮助显示。
  • ……

cli 开源在github上 https://github.com/mkideal/cli

入门介绍

命令行程序虽然没有华丽的界面,但是在服务器端,命令行程序是不可或缺的,而且在很多时候比图形界面更加好用。在unix/linux操作系统上命令行程序极其常见,系统上预装大量程序。 cli 这个工具正是用来便捷构建这种命令行程序的go语言库。 先看一个简单的示例:

package mainimport (	"github.com/mkideal/cli")type argT struct {	cli.Helper}func main() {	cli.Run(&argT{}, func(ctx *cli.Context) error {		argv := ctx.Argv().(*argT)		if argv.Help {			ctx.WriteUsage()		} else {			ctx.String("hello\n")		}		return nil	})}
Copy after login

编译运行这段代码

$ go build -o app$ ./apphello$ ./app -hOptions:  -h, --help     display help
Copy after login

当然这段代码没有任何实质功能。代码第12行调用 cli 的 Run 函数,函数原型如下:

func Run(argv interface{}, fn func(*Context) error, descs ...string)
Copy after login

参数 argv 在执行时会通过解析命令行参数来赋值,然后塞进 Context 对象,最终传递给回调函数 fn 。在回调函数中通过 ctx.Argv() 获得 argv 。

本示例代码的 argT 继承于 cli.Helper ,它的定义如下:

type Helper struct { Help bool `cli:"!h,help" usage:"display help"`}
Copy after login

好了,下面创建一个实用一点的程序来做更详细的讲解。

一个简易的http服务器

package mainimport (	"fmt"	"net/http"	"github.com/mkideal/cli")type argT struct {	cli.Helper	Host string `cli:"H,host" usage:"specify host" dft:"0.0.0.0"`	Port uint16 `cli:"p,port" usage:"specify port" dft:"8080"`	Dir  string `cli:"d,dir" usage:"static files directory" dft:"./"`}func main() {	cli.SetUsageStyle(cli.ManualStyle)	cli.Run(new(argT), func(ctx *cli.Context) error {		argv := ctx.Argv().(*argT)		if argv.Help {			ctx.WriteUsage()			return nil		}		http.Handle("/", http.FileServer(http.Dir(argv.Dir)))		addr := fmt.Sprintf("%s:%d", argv.Host, argv.Port)		ctx.String("listening on %s\n", addr)		http.ListenAndServe(addr, nil)		return nil	})}
Copy after login

在这个例子里,参数对象 argT 多了几个有用的字段: Host Port Dir

还是先编译运行一下

$ go build -o httpd$ ./httpd -h
Copy after login

好了,现在创建一个 html 目录,然后新建一个文件 index.html ,内容为

<h1 id="Hello-this-is-my-http-server">Hello, this is my http server!</h1>
Copy after login

然后启动 http server

$ mkdir html$ echo "<h1 id="Hello-this-is-my-http-server">Hello, this is my http server!</h1>" > html/index.html$ ./httpd -d htmllistening on 0.0.0.0:8080
Copy after login

现在通过浏览器访问 127.0.0.1:8080 就可以看到

你还可以指定别的端口,而非默认的端口8080,比如指定端口为3000

可以这样启动

$ ./httpd -d html --port=3000
Copy after login

或者

$ ./httpd -d html --port 3000
Copy after login

或者

$ ./httpd -d html -p=3000
Copy after login

或者

$ ./httpd -d html -p 3000
Copy after login

接下来讲述一下出现在参数定义中的标签,它们是解析参数以及显示帮助时器关键作用的因素。

标签cli,usage,dft

cli 支持4个标签

  • cli - 参数flag名,如示例中的 cli:"h,help" cli:"H,host" 等
  • usage - 参数使用描述,是会显示在帮助中的文本
  • dft - 指定参数默认值,可以指定环境变量为默认值,比如这样 dft:"$HOME"
  • name - 参数引用名,并无实质功能

创建命令行程序的命令行工具 clier goplus

clier 是 mkideal/cli 下的一个命令行程序,它也是使用 cli 构建的。 clier 用于创建一条命令,比如这样

$ clier hello$ clier -s "this is hello command's description" hello
Copy after login

goplus 的 new 子命令可以构建完整的基于 cli 的命令行程序。使用示例

$ goplus new hello # 最基本的单命令程序$ goplus new -t http httpd # 通过 `-t` 参数指定程序类型为`http`$ goplus new -t tree demo # 基本的多命令程序
Copy after login

本文只是一个 cli 的简要介绍。下面几篇是关于 cli 的更详细的介绍

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

What is an example of a starting tag in HTML? What is an example of a starting tag in HTML? Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

How to implement adaptive layout of Y-axis position in web annotation? How to implement adaptive layout of Y-axis position in web annotation? Apr 04, 2025 pm 11:30 PM

The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? How to use CSS3 and JavaScript to achieve the effect of scattering and enlarging the surrounding pictures after clicking? Apr 05, 2025 am 06:15 AM

To achieve the effect of scattering and enlarging the surrounding images after clicking on the image, many web designs need to achieve an interactive effect: click on a certain image to make the surrounding...

Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Why do you need to call Vue.use(VueRouter) in the index.js file under the router folder? Apr 05, 2025 pm 01:03 PM

The necessity of registering VueRouter in the index.js file under the router folder When developing Vue applications, you often encounter problems with routing configuration. Special...

See all articles