生成安裝包
系統執行
go build (-x 可以看到具體都執行了哪些操作)
混編
#如果我們想生成linux和windows上的程序,只要通過一下命令:
$gox -os "windows linux" -arch amd64
1.編譯window 64位:
gox -osarch="windows/amd64" ./
2.編譯mac 64位:
gox -osarch = "darwin/amd64" ./
3.編譯Linux 64位:
gox -osarch="linux/amd64" ./
執行命令包
- linux(./main 編譯後的文件可執行採集 ./main & 後臺運行)
- Windows(直接運行main.exe GoModTest.exe -name 123)
注意:
現象:同一個文件夾下面有多個go文件,a.go,b.go,c.go,其中main在a.go中,直接go run a.go,報undefined 錯誤12
原因:go在run之前會先進行編譯操作,而在此處的編譯它只會以這個a.go爲準,導致其他幾個引用文件中的方法出現找不到的情況
(而採用go build的方式又不一樣,他會自動查找引用文件並打包)123
解決辦法:go run a.go b.go c.go
(重點)自定義交互命令
1.指定加載的配置文件
./main -c 指定加載的配置文件
2.例如獲取版本號-v
[root@hu mq]# ./mqbeat_linux_amd64 -v
1.0.0
main.go代碼如下
if util.SliceContainString(os.Args, "-v") {
fmt.Printf("%v\n", config.Version)
os.Exit(0)
}
os.Args作爲數組的輸出裏面可以取到具體的值
E:\Workplace_Go\src\GoModTest>go run main.go -v 200
[C:\Users\Admin\AppData\Local\Temp\go-build184099962\b001\exe\main.exe -v 200]
3.獲取幫助信息-h
[root@hu mq]# ./mqbeat_linux_amd64 -h
Usage of Websphere_MQbeat:
-E value
Configuration overwrite (default null)
-N Disable actual publishing for testing
-T test mode with console output
-c value
Configuration file, relative to path.config (default beat.yml)
-configtest
Test configuration and exit.
-cpuprofile string
Write cpu profile to file
-httpprof string
Start pprof http server
-memprofile string
Write memory profile to this file
-path.config value
Configuration path
-path.data value
Data path
-path.home value
Home path
-path.logs value
Logs path
-reload
reload config
-setup
Load the sample Kibana dashboards
-strict.perms
Strict permission checking on config files (default true)
-version
Print the version and exit
Informations:
Version= 1.0.0
BuildCommit=
BuildTime= 2019/06/26
GoVersion= 1.12.1
main.go代碼如下
if util.SliceContainString(os.Args, "-h") {
buf := bytes.NewBufferString("Usage of " + config.AppName + ":\n")
flag.CommandLine.SetOutput(buf)
flag.PrintDefaults()
fmt.Printf("%v", buf.String())
fmt.Println("Informations:")
fmt.Printf(" Version= %v\n", config.Version)
fmt.Printf(" BuildCommit= %v\n", config.BuildCommit)
fmt.Printf(" BuildTime= %v\n", config.BuildTime)
fmt.Printf(" GoVersion= %v\n", config.GoVersion)
os.Exit(0)
}
config.go代碼如下
var (
AppName = "MQbeat"
Version = "1.0.0"
)
交互方式命令行參數Flag:
在 go 標準庫中提供了一個包:flag,方便進行命令行解析
1.flag.Parse()要放在main函數體的第一行
var name string
flag.StringVar(&name, "name", "everyone", "The greeting object.")
flag.Parse()
fmt.Println(name)
flag.BoolVar(&h, "h", false, "this help")
flag.BoolVar(&v, "v", false, "show version and exit")
flag.Int、flag.Bool、flag.String這樣的函數格式都是一樣的。
參數的說明如下:
&name:爲接收到的值,具體指爲name。
第一個arg表示參數名稱,在控制檯的時候,提供給用戶使用。
第二個arg表示默認值,如果用戶在控制檯沒有給該參數賦值的話,就會使用該默認值。
第三個arg表示使用說明和描述,在控制檯中輸入-arg的時候會顯示該說明,類似-help。