1. 标准命令简述

GoGo
gofmt

2. 标准命令使用

2.1 go build

Gogo build
go build
go buildexportGOPATH
export GOPATH=/home/wohu/gocode 
go build -o main main.go
./main

2.1.1 无参数编译

GOPATH
wohu@wohu:~/gocode/src$ tree -L 2
└── main
    ├── main.go
    └── upload.go
upload.go
package main

import "fmt"

func upload() {
        fmt.Println("This is upload function ")
}
main.go
package main

func main() {
        upload()
}
wohu@wohu:~/gocode/src$ 
wohu@wohu:~/gocode/src$ cd main/
wohu@wohu:~/gocode/src/main$ go build
wohu@wohu:~/gocode/src/main$ ls
main  main.go  upload.go
wohu@wohu:~/gocode/src/main$ ./main 	# 执行 main 后的输出内容
This is upload function 
go buildgogo buildupload.gomain.gomain

2.1.2 go build + 文件列表

go buildgo build
go build file1.go file2.go……

注意:使用“go build+文件列表”方式编译时,可执行文件默认选择文件列表中第一个源码文件作为可执行文件名输出

wohu@wohu:~/gocode/src/main$ go build upload.go main.go 
wohu@wohu:~/gocode/src/main$ ls
main.go  upload  upload.go
wohu@wohu:~/gocode/src/main$ ./upload 
This is upload function 
wohu@wohu:~/gocode/src/main$ 
wohu@wohu:~/gocode/src/main$ ls
main.go  upload.go
wohu@wohu:~/gocode/src/main$ go build main.go upload.go 
wohu@wohu:~/gocode/src/main$ ls
main  main.go  upload.go
wohu@wohu:~/gocode/src/main$ ./main 
This is upload function 
-o
wohu@wohu:~/gocode/src/main$ ls
main.go  upload.go
wohu@wohu:~/gocode/src/main$ go build -o test main.go upload.go 
wohu@wohu:~/gocode/src/main$ ls
main.go  test  upload.go
wohu@wohu:~/gocode/src/main$ ./test 
This is upload function 
wohu@wohu:~/gocode/src/main$ 

使用“go build+文件列表”编译方式编译时,文件列表中的每个文件必须是同一个包的 Go 源码

Go

2.1.3 go build + 包

GOPATH

代码格式如下:

wohu@wohu:~/gocode/src$ tree -L 3 
└── mypackage
    ├── main.go
    └── upload
        └── upload.go
main.go
package main

import "mypackage/upload"

func main() {
	upload.Demo()
}

upload.go
package upload

import "fmt"

func Demo() {
	fmt.Println("This is upload function ")
}

编译命令:

wohu@wohu:~/gocode/src$ export GOPATH=/home/wohu/gocode
wohu@wohu:~/gocode/src$ go build  -o main mypackage/
wohu@wohu:~/gocode/src$ ls
github.com  golang.org  main  mypackage
wohu@wohu:~/gocode/src$ ./main 
This is upload function 
wohu@wohu:~/gocode/src$ 
GOPATHGOPATHGOPATHsrc
...
$ cd $GOPATH/src/gopl.io/ch1/helloworld
$ go build

或者:

$ cd anywhere
$ go build gopl.io/ch1/helloworld

或者:

$ cd $GOPATH
$ go build ./src/gopl.io/ch1/helloworld

但不能这样:

$ cd $GOPATH
$ go build src/gopl.io/ch1/helloworld
Error: cannot find package "src/gopl.io/ch1/helloworld".
-omainGOPATHsrc
go build
-v-p n-a-n-x-race-o-work-gcflags""go tool compilego build -gcflags "-l -m"-ldflags""go tool linkgo build -ldflags "-w -s"-wgdb-s
go build
-a
-i
go build-xgo build-ngo build-vgo build-a

2.1.4 跨平台编译

macOSLinuxWindows

使用示例:

CGO_ENABLED=0  GOOS=linux  GOARCH=amd64  go build main.go

参数说明

CGO_ENABLEDCGOgolangCGO_ENABLED=0CGOCGOGOOSmacdarwinlinuxlinuxwindowswindowsfreebsdandroidGOARCHx86amd64armAndroidiOSWin mobile
CPUGOOSGOARCH
GOOSGOARCHmacOS AMD64Linux AMD64
$ GOOS=linux GOARCH=amd64 go build ./main.go
nvidia@tegra-ubuntu:~$ uname -a
Linux tegra-ubuntu 4.4.38-tegra #1 SMP PREEMPT Fri Jul 28 09:55:22 PDT 2017 aarch64 aarch64 aarch64 GNU/Linux
root@orangepizerolts:/tmp# uname -a
Linux orangepizerolts 5.4.27-sunxi #2.0.8 SMP Tue Jun 9 18:36:35 CST 2020 armv7l armv7l armv7l GNU/Linux
aarch64armv7larm
GOOS=linux GOARCH=arm go build ./main.go
GolangCGOCGO_ENABLED=0
MacLinuxWindows
$ CGO_ENABLED=0 GOOS=linux GOARCH=amd64    go build main.go
$ CGO_ENABLED=0 GOOS=windows GOARCH=amd64    go build main.go
LinuxMacWindows
$ CGO_ENABLED=0 GOOS=darwin GOARCH=amd64     go build main.go
$ CGO_ENABLED=0 GOOS=windows GOARCH=amd64    go build main.go
WindowsMacLinux
$ SET CGO_ENABLED=0 SET GOOS=darwin SET GOARCH=amd64   go build main.go
$ SET CGO_ENABLED=0 SET GOOS=linux SET GOARCH=amd64    go build main.go

2.2 go clean

Gogo clean
go buildgo test-cgo installgo build
go clean
-igo install-n-r-x-cachego build-testcache

使用演示:

wohu@wohu:~/gocode/src/mypackage$ go build -race -v   -o  main ../mypackage/
wohu@wohu:~/gocode/src/mypackage$ go clean -n
cd /home/wohu/gocode/src/mypackage
rm -f mypackage mypackage.exe mypackage.test mypackage.test.exe main main.exe
wohu@wohu:~/gocode/src/mypackage$ ls
main  main.go  upload
wohu@wohu:~/gocode/src/mypackage$ go clean -x 
cd /home/wohu/gocode/src/mypackage
rm -f mypackage mypackage.exe mypackage.test mypackage.test.exe main main.exe
wohu@wohu:~/gocode/src/mypackage$ ls
main.go  upload
wohu@wohu:~/gocode/src/mypackage$ 

2.3 go run

go runmain()
wohu@wohu:~/gocode/src/mypackage$ ls
main.go  upload
wohu@wohu:~/gocode/src/mypackage$ go run main.go 
This is upload function 
go run
go run
go run
go build

2.4 go fmt

Gogofmtgofmtgo fmt
gofmtcli.go.go
gofmt
标记名称标记描述
-l仅把那些不符合格式化规范的、需要被命令程序改写的源码文件的绝对路径打印到标准输出。而不是把改写后的全部内容都打印到标准输出。
-w把改写后的内容直接写入到文件中,而不是作为结果打印到标准输出。
-r添加形如“a[b:len(a)] -> a[b:]”的重写规则。如果我们需要自定义某些额外的格式化规则,就需要用到它。
-s简化文件中的代码。
-d只把改写前后内容的对比信息作为结果打印到标准输出。而不是把改写后的全部内容都打印到标准输出。命令程序将使用 diff 命令对内容进行比对。在 Windows 操作系统下可能没有 diff 命令,需要另行安装。
-e打印所有的语法错误到标准输出。如果不使用此标记,则只会打印每行的第 1 个错误且只打印前 10 个错误。
-comments是否保留源码文件中的注释。在默认情况下,此标记会被隐式的使用,并且值为 true。
-tabwidth此标记用于设置代码中缩进所使用的空格数量,默认值为 8。要使此标记生效,需要使用“-tabs”标记并把值设置为 false。
-tabs是否使用 tab(‘\t’)来代替空格表示缩进。在默认情况下,此标记会被隐式的使用,并且值为 true。
-cpuprofile是否开启 CPU 使用情况记录,并将记录内容保存在此标记值所指的文件中。
go fmt path/to/your/package
gofmttabgofmt

go fmt 和 gofmt 区别:

gofmtGogo fmtgo fmtgofmt
go fmt-n-x
-ngo fmt-xgo fmt

2.5 go install

go installgo buildgo buildgo installGOPATHpkgGOPATHbin
$GOPATH/pkg$GOPATH/bin
go install
go installGOPATHgo installGOPATHbingo installgo installGOPATHbin-oGOPATHpkg

2.6 go get

go get
BitBucketGitHubGoogle CodeLaunchpadgo getGitSVNHG

这个命令在内部实际上分成了两步操作:

go install
go getPATHgo get
go get
$ go get github.com/davyxu/cellnet
  • go get 使用时的附加参数
-v-u-d-insecure-t-fix

2.7 go doc

2.7.1 go doc 命令

 
$ go doc time
package time // import "time"

Package time provides functionality for measuring and displaying time.

const Nanosecond Duration = 1 ...
func After(d Duration) <-chan Time
func Sleep(d Duration)
func Since(t Time) Duration
func Now() Time
type Duration int64
type Time struct { ... }
...many more...

或者是某个具体的包成员:

$ go doc time.Since
func Since(t Time) Duration

    Since returns the time elapsed since t.
    It is shorthand for time.Now().Sub(t).

或者是一个方法:

$ go doc time.Duration.Seconds
func (d Duration) Seconds() float64

    Seconds returns the duration as a floating-point number of seconds.

2.7.2 go doc 页面

go doc godoc
godoc
$ godoc -http :8000
-analysis=type-analysis=pointer

2.8 go list

go list
$ go list github.com/go-sql-driver/mysql
github.com/go-sql-driver/mysql
go list"..."
$ go list ...
archive/tar
archive/zip
bufio
bytes
cmd/addr2line
cmd/api
...many more...

或者是特定子目录下的所有包:

$ go list gopl.io/ch3/...
gopl.io/ch3/basename1
gopl.io/ch3/basename2
gopl.io/ch3/comma
gopl.io/ch3/mandelbrot
gopl.io/ch3/netflag
gopl.io/ch3/printints
gopl.io/ch3/surface

或者是和某个主题相关的所有包:

$ go list ...xml...
encoding/xml
gopl.io/ch7/xmlselect
go list-json JSON
$ go list -json hash
{
    "Dir": "/home/gopher/go/src/hash",
    "ImportPath": "hash",
    "Name": "hash",
    "Doc": "Package hash provides interfaces for hash functions.",
    "Target": "/home/gopher/go/pkg/darwin_amd64/hash.a",
    "Goroot": true,
    "Standard": true,
    "Root": "/home/gopher/go",
    "GoFiles": [
            "hash.go"
    ],
    "Imports": [
        "io"
    ],
    "Deps": [
        "errors",
        "io",
        "runtime",
        "sync",
        "sync/atomic",
        "unsafe"
    ]
}
-ftext/templatestrconvjoin
$ go list -f '{{join .Deps " "}}' strconv
errors math runtime unicode/utf8 unsafe
Windowstemplate: main:1: unclosed action" "
$ go list -f "{{join .Deps \" \"}}" strconv
compress
$ go list -f '{{.ImportPath}} -> {{join .Imports " "}}' compress/...
compress/bzip2 -> bufio io sort
compress/flate -> bufio fmt io math sort strconv
compress/gzip -> bufio compress/flate errors fmt hash hash/crc32 io time
compress/lzw -> bufio errors fmt io
compress/zlib -> bufio compress/flate errors fmt hash hash/adler32 io
Windows
$ go list -f "{{.ImportPath}} -> {{join .Imports \" \"}}" compress/...

2.9 go tool

toolgocompilego tool cmd/compilecompile
go tool compile [flags] file...
fileGo[flags]
-N-S-S –S-blockprofile fileblock profilefile-cpuprofile filecpu profilefile-dynlinkGo symbols-e-h-l-lang version-m-memprofile filememory profilefile-memprofilerate rateruntime.MemProfileRate-mutexprofile filemutex profilefile-race-traceprofile fileexecution tracefile
Go 1.1raceraceGo
$ go test -race mypkg
$ go run -race mysrc.go
$ go build -race mycmd
$ go install -race mypkg
go racego race
deferrecoverGoroutineGoroutinedeferrecover

2.9 go version

Gogo version
$ go version
go version go1.13.6 linux/amd64
$
go versiongo help version
$ go help version
usage: go version [-m] [-v] [file ...]

Version prints the build information for Go executables.

Go version reports the Go version used to build each of the named
executable files.

If no files are named on the command line, go version prints its own
version information.

If a directory is named, go version walks that directory, recursively,
looking for recognized Go binaries and reporting their versions.
By default, go version does not report unrecognized files found
during a directory scan. The -v flag causes it to report unrecognized files.

The -m flag causes go version to print each executable's embedded
module version information, when available. In the output, the module
information consists of multiple lines following the version line, each
indented by a leading tab character.

See also: go doc runtime/debug.BuildInfo.
GoGo

2.10 go vet

go vetGo
go vetLintergo tool vet help
go vetGoLintergolangci-lintgolangci-lintLintergolangci-lintLintergolangci-lint help linters