Go中强大的命令行应用程序(附代码示例)

173 阅读1分钟

"Go中强大的Cli应用程序 "工作区

这不是一个 "真正的 "项目,因为它不接受PR,也不应该被任何人当作真正的应用程序来使用或分叉。

这是我学习书中概念的工作空间。

这也是我的 "笔记本",用来记录如何在Go中做事或如何管理一个Go项目。

章节|应用程序

第01章 - 你的第一个Go命令行程序 - wordcount/wc

如何安装

我在二进制文件中加入了cli- 前缀,这样我就不会在我的PATH 中用这个版本替换系统版本的wc

使用go install

$ go install github.com/vpayno/powerful-cli-apps-in-go-workspace/cmd/cli-wc@latest

$ git clone https://github.com/vpayno/powerful-cli-apps-in-go-workspace.git
$ cd powerful-cli-apps-in-go-workspace
$ go generate
# go install ./cmd/cli-wc/cli-wc.go

用法

$ ./scripts/go-cmd run ./... -h
go generate ./...
go generate: creating /home/vpayno/git_vpayno/powerful-cli-apps-in-go-workspace/cmd/cli-wc/./.version.txt

v0.0.0
v0.0.0-8-g275e726
275e72657a4241eaddc5ce90bbb1aaa0c6a0289b
2022-08-08T07:00:12Z


real	0m0.144s
user	0m0.102s
sys	0m0.140s

Usage of /tmp/go-build1277001378/b001/exe/cli-wc:
  -V	show the app version
  -b	count bytes instead of words
  -l	count lines instead of words
  -v	verbose mode

real	0m0.314s
user	0m0.301s
sys	0m0.290s
go run ./... -h

git restore ./cmd/cli-wc/.version.txt

real	0m0.004s
user	0m0.003s
sys	0m0.003s

例子

  • 显示版本
$ go generate ./...
go generate: creating /home/vpayno/git_vpayno/powerful-cli-apps-in-go-workspace/cmd/cli-wc/./.version.txt

v0.0.0
v0.0.0-8-g275e726
275e72657a4241eaddc5ce90bbb1aaa0c6a0289b
2022-08-08T07:25:49Z

$ go build ./cmd/cli-wc/cli-wc.go

$ printf "%s\n" one two three four five | ./cli-wc -V

Word Count Version: v0.0.0

git version: v0.0.0-8-g275e726
   git hash: 275e72657a4241eaddc5ce90bbb1aaa0c6a0289b
 build time: 2022-08-08T07:25:49Z
  • 计算字数
$ printf "%s\n" one two three four five | ./cli-wc
5
$ printf "%s\n" one two three four five | ./cli-wc -v
Word Count Version v0.0.0

word count: 5
  • 计算行数
$ printf "%s\n" one two three four five | ./cli-wc -l
5
$ printf "%s\n" one two three four five | ./cli-wc -l -v
Word Count Version v0.0.0

line count: 5
  • 计算字节数
$ printf "%s\n" one two three four five | ./cli-wc -b
19
$ printf "%s\n" one two three four five | ./cli-wc -b -v
Word Count Version v0.0.0

byte count: 19