picture


Introduction |  This article mainly shares some tools related to Golang, briefly introduces the functions and usage scenarios of the tools, and will not introduce their use in detail. The listed tools are not the most complete. For details, you can refer to the links or search and learn by yourself.


Go official tools can use the go help xxx command to view the help documentation, such as viewing the parameter markers and usage documentation of go get:


go help get


You can refer to the official documentation of Golang: https://golang.google.cn/cmd/go/


1. G0 official tools


(1) go get


This command can download or update the specified code package and its dependent packages from the Internet according to the requirements and actual conditions. After downloading, it will be automatically compiled. Generally, go get is sufficient for referencing dependencies.


refer to:


go get -u "github.com/VictoriaMetrics/fastcache"

refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261349

(2) go build

This command is used to compile the source files or code packages we specify and their dependencies. Commonly used tags for commands are described below:

picture

The compilation process is output to the file: go build -x > result 2>&1, because go build -x finally writes the log to the standard error stream.

If you only need to specify parameters when compiling a specific package, you can refer to the format of package name=parameter list, such as go build -gcflags='log=-N -l' main.go

refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261347 _

(3) go install

This command is used to compile and install the specified code package and their dependent packages. When the dependencies of the specified code package have not been compiled and installed, this command will process the dependencies first. As with the go build command, package arguments passed to the go install command should be provided as import paths.

Also, most flags of the go build command can also be used with the go install command. In fact, the go install command only does one more thing than the go build command, that is: install the compiled result file to the specified directory.

refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261348 _

(4) go fmt and gofmt

The Golang development team has formulated a unified official code style, and launched the gofmt tool (gofmt or go fmt) to help developers format their code into a unified style.

gofmt is a cli program that reads standard input first. If a file path is passed in, it will format the file. If a directory is passed in, it will format all .go files in the directory. If no parameters are passed, it will format All .go files in the current directory.

gofmt does not simplify the code by default, use the -s parameter to enable the simplified code function

gofmt is an independent cli program, and there is also a go fmt command in go. The go fmt command is a simple encapsulation of gofmt. go fmt adds -l -w parameters when calling gofmt, which is equivalent to executing gofmt -l -w

refer to:

https://blog.csdn.net/whatday/article/details/97682094

(5) go env

This command is used to print the environment information of Go language. Common general environment information is as follows:

picture

Set or modify environment variable values:

go env -w GOPROXY="https://goproxy.com,direct"

refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261359

(6) go run 

This command can run command source files, and can only accept one command source file and several library source files (must belong to the main package) as file parameters, and cannot accept test source files. It checks the type of the source file when it is executed. If there are multiple or no command source files in the parameters, the go run command will only print an error message and exit without continuing execution.

After passing the parameter check, the go run command will compile the command source file in the parameters and store the compiled executable file in the temporary working directory.


refer to:

https://www.kan cloud.cn/cattong/go_command_tutorial/261352

(7) go test

This command is used to test the program written in Go language. This test is based on the code package. The command will automatically test each specified code package. Of course, the premise is that the test source code file exists in the specified code package.

refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261353

(8) go clean

This command will delete some files and directories generated when other commands are executed.

refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261350 _

(9) go list

The function of this command is to list the information of the specified code package. As with other commands, we need to give the code package in the way of the code package import path. There can be more than one package of code given. The directories corresponding to these code packages must directly store Go language source files, and the files in their subdirectories are not included.

The role of the flag -e is to load and analyze the specified code package in fault-tolerant mode. In this case, if the command program encounters an error during loading or analysis, it will only record it internally, and will not print the error message directly.

To see error messages use the -json flag. The function of this tag is to print out the structure instance of the code package in JSON style. The -m flag prints out modules instead of packages.

# cd yky-sys-backend/cmd/bidengine# go list -json -m{        "Path": "github.com/Project/test",        "Main": true,        "Dir": "/data/test",        "GoMod": "/data/test/go.mod",        "GoVersion": "1.15"} # 进入到.go文件的目录下,可以把文件依赖打印出来go list -m -json

 refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261354 _ _

(10) go mod xxx

  • go mod init

This command initializes and writes a new go.mod to the current directory, effectively creating a new module rooted in the current directory. The file go.mod must not exist. If possible, init guesses the module path from import comments (see "go help importpath") or from version control configuration. To override this guess, supply the module path as the parameter module for the current project name. for example:

go mod init demo

refer to:

https://www.jianshu.com/p/f6d2d6db2bca

  • go mod tidy

This command ensures that go.mod is consistent with the source code in the module. It adds any missing modules necessary to build the current module's packages and dependencies, and removes unused modules that do not provide any valuable packages. It will also add any missing entries to go.mod and remove any unwanted entries.

refer to:

https://www.jianshu.com/p/f6d2d6db2bca

  • go mod vendor

This command resets the main module's vendor directory to contain all the packages needed to build and test all of the main module's packages. Test code for packages in vendor is not included. Copy the package downloaded by GOPATH or GOROOT to the vendor directory under the project. If you do not use vendor to isolate project dependencies, you do not need to use this command to copy dependencies.


refer to:

https://www.jianshu.com/p/f6d2d6db2bca

  • go mod download

This command downloads the module with the specified name, which can be used to select the module matching pattern that the main module depends on, or the module query in the form of path@version. If download takes no parameters, it means all dependencies of the main module. Download will only download dependencies, not compile dependencies, which is different from get.


refer to:

https://www.jianshu.com/p/f6d2d6db2bca

  • go mod edit

This command provides a command line interface for editing go.mod, mainly for tools or scripts. It only reads go.mod; it doesn't look for information involving modules. By default, edit reads and writes the main module's go.mod file, but a different target file can also be specified after the flag.

Reference :

https://www.jianshu.com/p/f6d2d6db2bca

  • go mod graph

This command prints a graph of dependencies between modules in text form. Each line of output has two fields (separated by spaces); the module and one of all its dependencies. Every module is marked with a string of the form path@version (except the main module, which does not have the @version suffix).


refer to:

https://www.jianshu.com/p/f6d2d6db2bca

  • go mod verify

This command checks whether the dependencies of the current module stored in the locally downloaded source code cache have not been modified since the download. If all modules have not been modified, print "all modules verified". Otherwise, report which module has been modified and cause "go mod" to exit with a non-zero status.


refer to:

https://www.jianshu.com/p/f6d2d6db2bca

  • go mod why


This command outputs a block of references for each package or module. Each block begins with a comment line "#package" or "#module", giving the target package or module. Subsequent lines give the path through the import graph, one package per line. Each block is separated by a blank line, and if the package or module is not referenced by the main module, the subsection will display a single parenthesized prompt to indicate that fact.

refer to:

https://www.jianshu.com/p/f6d2d6db2bca

(11) go tool xxx

The executable file of go tool is in the pkg/tool ​​directory of GOROOT or GOPATH. Go doc cmd can view the usage instructions of specific cmd, such as:

go doc pprof

  • go tool pprof

In Golang, performance analysis can be performed corresponding to the runtime of the program through the pprof tool, including real-time information such as CPU, memory, and Goroutine.

refer to:

https://www.kancloud.cn/cat tong/go_command_tutorial/261357

  • go tool trace

This command can trace the request link, clearly understand the call stack of the entire program, and capture a lot of information through the tracer.


refer to:

https://zhuanlan.zhihu.com/p/410590497

  • go tool compile

This command can compile Go files to generate assembly code. The -N parameter indicates that compilation optimization is prohibited, -l indicates that inlining is prohibited, and -S indicates that the assembly is printed, such as

# 会生成main.o的汇编文件go tool compile -S main.go

  • go tool vet and go vet

This command is a simple tool for checking static errors in Go language source code.

The go vet command is a simple wrapper around the go tool vet command. It will first load and analyze the specified code package, and pass the relative paths of all Go language source files in the specified code package and files ending with ".s" as parameters to the go tool vet command. Among them, the file ending with ".s" is the source file of assembly language. If the arguments to the go vet command are paths to Go language source files, these arguments are passed directly to the go tool vet command.


refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261356

  • go tool doc and go doc


This command prints documents attached to Go language program entities. We can view its documentation by passing the identifier of the program entity as an argument to this command.

The so-called program entities in Go language refer to variables, constants, functions, structures and interfaces. The identifiers of program entities are the names that represent them.

refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261351

  • go tool addr2line


This command converts the address of the call stack into a file and line number.

Usage:     go tool addr2line binary Addr2line reads hexadecimal addresses, one per line and with optional 0xprefix, from standard input. For each input address, addr2line prints twooutput lines, first the name of the function containing the address andsecond the file:line of the source code corresponding to that address. This tool is intended for use only by pprof; its interface may change or itmay be deleted entirely in future releases.

  • go tool asm

This command can compile the assembly file into a .o file, and the subsequent .o file can be used to generate a .a archive file. The file parameter of the command must be an assembly file.

Usage:     go tool asm [flags] file The specified file must be a Go assembly file. The same assembler is usedfor all target operating systems and architectures. The GOOS and GOARCHenvironment variables set the desired target.

  • go tool buildid


Each Go binary has a unique Build ID, see  src/cmd/go/internal/work/buildid.go for details  . The Go Build ID can be viewed with the following command:

go tool buildid

refer to:

https://www.anquanke.com/post/id/215419

  • go tool cgo

This command allows us to create a Go language source file that can call C language code. This allows us to use Go language code to encapsulate some C language code bases and provide them for Go language code or projects.

refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261358

  • go tool cover


This command generates an html file based on the code coverage statistics generated during the unit testing process, which can be opened and displayed locally.

go test -coverprofile=a.outgo tool cover -html=a.out -o coverage.html

Coverage tools can record not only whether a branch was taken, but also how many times a branch was taken.

go test -covermode=set|count|atomic:
-covermode:

set: default mode, whether to perform statistics 

count: count

atomic: a concurrency-safe version of count, only used when precise statistics are required

Check the coverage of each function with go tool cover -func=count.out.

refer to:

https://blog.csdn.net/xhdxhdxhd/article/details/120424848

  • go tool dist

The dist tool is a bootstrap tool belonging to go that is responsible for building C programs (like the Go compiler ) and an initial bootstrap copy of the Go tools. It also works as a catch-all shell script to replace previously done odd jobs. The tool can be operated with the "go tool dist" command.

go tool distusage: go tool dist [command]Commands are: banner         print installation bannerbootstrap      rebuild everythingclean          deletes all built filesenv [-p]       print environment (-p: include $PATH)install [dir]  install individual directorylist [-json]   list all supported platformstest [-h]      run Go test(s)version        print Go version

Use go tool dist list to output the operating systems and architectures supported by the currently installed version of Go.


Reference: https://blog.csdn.net/byxiaoyuonly/article/details/112492264

  • go tool fix and go fix


This command will correct the old version of the code in all Go language source files of the specified code package to the new version of the code. The version mentioned here is the version of the Go language. All Go language source files of a code package exclude files in its subpackages (if any). Correction operations include replacing code that calls the old program with code that calls the new program, replacing the old syntax with the new syntax, and so on.

This tool is actually very useful. In the process of upgrading and evolution of programming languages, it is inevitable to improve the outdated and insufficient syntax and standard library.

refer to:

https://www.kancloud.cn/cattong/go_command_tutorial/261355

  • go tool link


This command links Go archives such as static libraries, and links all their dependencies to generate an executable (including the main package).

go tool link [flags] main.aFlags:     -B note        Add an ELF_NT_GNU_BUILD_ID note when using ELF.        The value should start with 0x and be an even number of hex digits.    -D address        Set data segment address.    -E entry        Set entry symbol name.    -H type        Set executable format type.        The default format is inferred from GOOS and GOARCH.        On Windows, -H windowsgui writes a "GUI binary" instead of a "console binary."    -I interpreter        Set the ELF dynamic linker to use.    -L dir1 -L dir2        Search for imported packages in dir1, dir2, etc,        after consulting $GOROOT/pkg/$GOOS_$GOARCH.    -R quantum        Set address rounding quantum.    -T address        Set text segment address.    -V        Print linker version and exit. go tool compile -o calc.o -I pkg/linux_amd64 src/calc/calc.gogo tool link -o bin/calc -L pkg/linux_amd64 calc.o

refer to:

http://cache.baiducontent.com/

  • go tool nm

This command can view the command of the symbol table, which is equivalent to the nm command of the system, which is very useful. At the breakpoint, if you don't know the function symbol of the breakpoint, you can check it with this command (the command deals with binary program files), the first column is the address, the second column is the type, and the third column is the symbol. Equivalent to the nm command.

refer to:

https://studygolang.com/articles/29906

  • go tool objdump


This command can disassemble the binary tool, which is equivalent to the system objdump. The command parses the program file in binary format.

go tool objdump example.ogo tool objdump -s DoFunc example.o  // 反汇编具体函数

refer to:

https://studygolang.com/articles/29906

  • go tool pack


This command packages the binary into a static library.

go tool pack op file.a [name...] 参数op    c   append files (from the file system) to a new archive    p   print files from the archive    r   append files (from the file system) to the archive    t   list files from the archive    x   extract files from the archive go tool compile -o simplemath.o src/simplemath/add.go src/simplemath/sqrt.gogo tool pack c pkg/linux_amd64/simplemath.a simplemath.o

refer to:

http://cache.baiducontent.com/

  • go tool test2json

This command is used to convert the test executable into readable json format.

// 生成测试文件的可执行文件go  test string_concat_test.go -o string_concat.test go tool test2json ./string_concat.test -test.v // 输出{"Action":"output","Output":"testing: warning: no tests to run\n"}{"Action":"output","Output":"PASS\n"}{"Action":"pass"}

 refer to:

https://blog.csdn.net/weixin_33772442/article/details/112098085

  • godoc

This command can generate a local http service for official Go documents, you can view standard library and third-party library documents, and project documents online, but you need to write comments in a certain format.

// 安装godocgo get -v  golang.org/x/tools/cmd/godoc // 方式一godoc -http=:6060 // 方式二 :-play可以使用playground运行Example代码godoc -http=:6060 -play // 查看自己的项目文档,需要将其它路径下的项目代码目录建一个软链到GOROOT的src目录下,如cd $GOROOT/src; ln -s /data/my-project ./,在浏览器后面输入项目名即可http://127.0.0.1:6060/pkg/my-project/

The web page is as follows:

picture

Reference: https://www.fujieace.com/golang/godoc.html

2. Third-party tools


Go Tools and Components Rollup Project:

https://github.com/avelino/awesome-go

(1) delve

Native code debugging tool

Reference: https://github.com/go-delve/delve

(2) goconvey

goconvey is a test framework for Golang that can manage and run test cases, provide rich assertion functions, and support many web interface features.


参考:https://github.com/smartystreets/goconvey

(三)goleak

本地排查内存泄露的工具

参考:https://github.com/uber-go/goleak

(四)go-wrk

Go接口压测工具

参考:https://github.com/adjust/go-wrk

(五)golint

代码风格检查

参考:https://github.com/golang/lint

(六)revive

代码风格检查,比golint速度更快


参考:https://github.com/mgechev/revive

(七)gocode

代码自动补全工具,可以在vim中使用


参考:https://github.com/nsf/gocode

(八)godoctor

代码重构工具

参考:https://github.com/godoctor/godoctor

(九)gops

查看go进程和相关信息的工具,用于诊断线上服务。

参考:https://github.com/google/gops

(十)goreplay

GoReplay是一个开源网络监控工具,可以将实时HTTP流量捕获并重放到测试环境。

参考:https://github.com/buger/goreplay

https://blog.51cto.com/axzxs/5102596

(十一)depth

一个有用的Golang工具,Depth可帮助Web开发人员检索和可视化Go源代码依赖关系树。它可以用作独立的命令行应用程序或作为项目中的特定包。你可以通过在解析之前在Tree上设置相应的标志来添加自定义。

参考:https://github.com/KyleBanks/depth

(十二)go-swagger

该工具包包括各种功能和功能。Go-Swagger是Swagger 2.0的一个实现,可以序列化和反序列化swagger规范。它是RESTful API简约但强大的代表。

通过Go-Swagger,你可以swagger规范文档,验证JSON模式以及其他额外的规则。其他功能包括代码生成,基于swagger规范的API生成,基于代码的规范文档生成,扩展了的字符串格式,等等。

参考:https://github.com/go-swagger/go-swagger

(十三)gox

交叉编译工具,可以并行编译多个平台。


参考:https://github.com/mitchellh/gox

(十四)gocyclo

gocyclo用来检查函数的复杂度。

# 列出了所有复杂度大于20的函数gocyclo -over 20 $(ls -d */ | grep -v vendor)
# 列出最复杂的5个gocyclo -top 5 $(ls -d */ | grep -v vendor)

参考:https://github.com/fzipp/gocyclo

(十五)deadcode

deadcode会告诉你哪些代码片段根本没用。

find . -type d -not -path "./vendor/*" | xargs deadcode

参考:https://github.com/tsenart/deadcode

(十六)gotype

gotype会对go文件和包进行语义(semantic)和句法(syntactic)的分析,这是google提供的一个工具。

find . -name "*.go" -not -path "./vendor/*" -not -path ".git/*" -print | xargs gotype -a

参考:https://golang.org/x/tools/cmd/gotype

(十七)misspell

misspell用来拼写检查,对国内英语不太熟练的同学很有帮助。

find . -type f -not -path "./vendor/*" -print | xargs misspell

参考:https://github.com/client9/misspell

(十八)staticcheck

staticcheck是一个超牛的工具,提供了巨多的静态检查,就像C#生态圈的 ReSharper一样。

# 安装:go install honnef.co/go/tools/cmd/staticcheck@latest# 使用:staticcheck main.go

参考:

https://staticcheck.io/docs/

https://github.com/dominikh/go-tools/tree/master/staticcheck

(十九)goconst

goconst会查找重复的字符串,这些字符串可以抽取成常量。

goconst ./… | grep -v vendor

参考:https://github.com/jgautheron/goconst

参考资料:

1.Go命令教程:

https://www.kancloud.cn/cattong/go_command_tutorial/261351

2.Golang指南:顶级Golang框架、IDE和工具列表:

https://zhuanlan.zhihu.com/p/30432648

3.Go代码检修工具集:

http://t.zoukankan.com/binHome-p-14149941.html

 作者简介


picture

罗元国

腾讯后台开发工程师

腾讯后台开发工程师,目前负责腾讯游戏广告推荐后台开发工作,在广告推荐和Golang性能优化方面有着丰富的开发经验。



 推荐阅读


深入浅出详解Knative云函数框架!

通俗易懂!图解Go协程原理及实战

C++一行代码实现任意系统函数Hook!

深入理解Linux的TCP三次握手!


picture

Reminder : Because the official account platform has changed the push rules, you need to click "like" and "watching" at the end of the article pushed by the official account, and the new article will appear in your subscription list for the first time~