1. 程式人生 > >GO語言 VSCode開發環境搭建 [Mac]

GO語言 VSCode開發環境搭建 [Mac]

Go是一個由Google團隊和開源社群的許多貢獻者開發的開源專案. 本文詳細記錄了Go開發環境搭建過程,包括Go安裝,IDE配置等。

系統環境配置

MacOS High Sierra
版本10.13.5

MacBook Pro (Retina, 15-inch, Mid 2015)
處理器 2.2 GHz Intel Core i7
記憶體 16 GB 1600 MHz DDR3
圖形卡 Intel Iris Pro 1536 MB

一、GO 安裝

Go官網提供了可用的Go列表,可以直接下載安裝。本文主要採用了homebrew工具進行安裝,其優點是簡單同時也能夠在需要的時候利用homebrew進行升級。(HomeBrew安裝教程參見

https://brew.sh/)

[email protected]:~/Workspace/ $brew info go

go: stable 1.10.3 (bottled), HEAD
Open source programming language to build simple/reliable/efficient software
https://golang.org
Not installed
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/go.rb
==> Requirements
Required: macOS >= 10.8 ✔
==> Options
--without-cgo
	Build without cgo (also disables race detector)
--without-race
	Build without race detector
--HEAD
	Install HEAD version
==> Caveats
A valid GOPATH is required to use the `go get` command.
If $GOPATH is not specified, $HOME/go will be used by default:
  https://golang.org/doc/code.html#GOPATH
You may wish to add the GOROOT-based install location to your PATH:
  export PATH=$PATH:/usr/local/opt/go/libexec/bin
[email protected]:~/Workspace $brew install go

Updating Homebrew...
warning: unable to access '/Users/zhongxiao.yzx/.config/git/ignore': Permission denied
warning: unable to access '/Users/zhongxiao.yzx/.config/git/attributes': Permission denied
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> Renamed Formulae
cdiff -> ydiff
==> Downloading https://homebrew.bintray.com/bottles/go-1.10.3.high_sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring go-1.10.3.high_sierra.bottle.tar.gz
==> Caveats
A valid GOPATH is required to use the `go get` command.
If $GOPATH is not specified, $HOME/go will be used by default:
  https://golang.org/doc/code.html#GOPATH
You may wish to add the GOROOT-based install location to your PATH:
  export PATH=$PATH:/usr/local/opt/go/libexec/bin
==> Summary

二、Go環境變數配置

Go安裝完成後,可以工作go env檢視環境Go相關的環境變數
[email protected]:~/Workspace $go env
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/zhongxiao.yzx/Library/Caches/go-build"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/zhongxiao.yzx/go"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.10.3/libexec"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.10.3/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/3l/nr_rmq_x0wd1nmg84kl9cfj00000gn/T/go-build353988632=/tmp/go-build -gno-record-gcc-switches -fno-common"
其中GOROOT,GOPATH是3個重要的環境變數
  • GOROOT: 安裝目錄
  • GOPATH: 日常開發的根目錄,該目錄在Go開發,編譯,安裝過程中起著重要的作用,例如 go get, go install等命令都會根據GOPATH來儲存相關的外掛,檔案等。該目錄不能和Go的安裝目錄一樣,這個目錄下面有三個子目錄: src、bin、pkg
  1. src 存放原始碼(比如:.go .c .h .s等)
  2. pkg 編譯後生成的檔案(比如:.a)
  3. bin 編譯後生成的可執行檔案(為了方便,可以把此目錄加入到$PATH變數中,如果有多個gopath,那麼使用${GOPATH//://bin:}/bin) 
  • GOBIN:是GOPATH下的bin目錄,該環境變數影響到go install命令
    在未設定GOBIN情況下
    [email protected]:~/Workspace/dev/golang/src$go install -x main.go
    go install: no install location for .go files listed on command line (GOBIN not set)
    在設定了GOBIN環境變數的情況下
    [email protected]:~/Workspace/dev/golang/src$go install -x main.go
    cd .
    /usr/local/Cellar/go/1.10.3/libexec/pkg/tool/darwin_amd64/link -o $WORK/b001/exe/a.out -importcfg $WORK/b001/importcfg.link -buildmode=exe -buildid=m26dg2-o1fDEe4lb1JZs/pcntLKDV1KQrpUm8zrkQ/FVueuXxUB9G0toBnk0P2/m26dg2-o1fDEe4lb1JZs -extld=clang $WORK/b001/_pkg_.a
    /usr/local/Cellar/go/1.10.3/libexec/pkg/tool/darwin_amd64/buildid -w $WORK/b001/exe/a.out # internal
    mkdir -p /Users/zhongxiao.yzx/Workspace/dev/golang/bin/
    mv $WORK/b001/exe/a.out /Users/zhongxiao.yzx/Workspace/dev/golang/bin/main
    rm -r $WORK/b001/
GOPATH在沒有配置環境變數的情況下,Go開發環境採用預設的配置
GOROOT="/usr/local/Cellar/go/1.10.3/libexec"
GOPATH="/Users/zhongxiao.yzx/go"

其中${HOME}是"/Users/zhongxiao.yzx/

[email protected]:~/Workspace $which go
/usr/local/bin/go

那麼為什麼GOROOT="/usr/local/Cellar/go/1.10.3/libexec"呢?

[email protected]:~/Workspace $ls -la /usr/local/bin/go
lrwxr-xr-x  1 zhongxiao.yzx  admin  26  6 28 09:13 /usr/local/bin/go -> ../Cellar/go/1.10.3/bin/go
[email protected]:~/Workspace $ls -la /usr/local/Cellar/go/1.10.3/bin/go
lrwxr-xr-x  1 zhongxiao.yzx  admin  17  6  7 07:50 /usr/local/Cellar/go/1.10.3/bin/go -> ../libexec/bin/go
可見/usr/local/bin/go實際上是對/usr/local/Cellar/go/1.10.3/ libexec/bin/go的引用

雖然go env以有預設的環境變數但是在終端中沒有預設Go環境變數的設定,因此在.bash_profile中設定如下

 #--------------------------------------------------
 # go environment variable
 export GOROOT="/usr/local/Cellar/go/1.10.3/libexec"
 export GOPATH="${HOME}/Workspace/dev/golang"
 export GOPATH="${GOPATH}/bin"
 export PATH="${PATH}:${GOPATH}:${GOPATH}/bin"
至此我們可以構建如下的Go程式,並在終端環境採用go build, go run等命令編譯執行Go程式
[email protected]:~/Workspace/dev/golang$tree -L 2
.
├── bin
├── pkg
└── src

    ├── main.go

// main.go
package main
import (
    "fmt"
)
func main() {
    fmt.Println("hello world")
}
[email protected]:~/Workspace/dev/golang/src$go -h
Go is a tool for managing Go source code.
Usage:
        go command [arguments]
The commands are:
        build       compile packages and dependencies
        clean       remove object files and cached files
        doc         show documentation for package or symbol
        env         print Go environment information
        bug         start a bug report
        fix         update packages to use new APIs
        fmt         gofmt (reformat) package sources
        generate    generate Go files by processing source
        get         download and install packages and dependencies
        install     compile and install packages and dependencies
        list        list packages
        run         compile and run Go program
        test        test packages
        tool        run specified go tool
        version     print Go version
        vet         report likely mistakes in packages
Use "go help [command]" for more information about a command.

三、VSCode Go開發環境配置

按照以上的步驟,我們已經建立了最原始的終端Go程式開發環境,但為了更加高效的進行大型Go程式的開發,需要搭建適合開發者的Go程式設計環境。
VSCode是流行的開源IDE,支援Go語言開發外掛(VSCode安裝參見https://code.visualstudio.com)

點選VSCode Extensions圖示,搜尋Go外掛,選擇Go進行安裝並重新載入Visual Studio Code。


VSCode外掛安裝依賴依賴GOPATH環境變數,雖然在第二部分已經配置了Go語言環境變數,但是在VSCode中GOPATH依然採用了預設值,因此需要在User Settings中設定go.gopath屬性。



設定完Go環境變數,可以在Go工程中建立main.go檔案,這時後VSCode會提示依賴缺失,提示安裝


Installing 9 tools at /Users/zhongxiao.yzx/Workspace/dev/golang/bin
  gocode
  gopkgs
  go-outline
  go-symbols
  guru
  gorename
  godef
  goreturns
  golint

Installing github.com/mdempsky/gocode SUCCEEDED
Installing github.com/uudashr/gopkgs/cmd/gopkgs SUCCEEDED
Installing github.com/ramya-rao-a/go-outline SUCCEEDED
Installing github.com/acroca/go-symbols SUCCEEDED
Installing golang.org/x/tools/cmd/guru SUCCEEDED
Installing golang.org/x/tools/cmd/gorename SUCCEEDED
Installing github.com/rogpeppe/godef SUCCEEDED
Installing github.com/sqs/goreturns SUCCEEDED
Installing github.com/golang/lint/golint SUCCEEDED

All tools successfully installed. You're ready to Go :).

當然也可以通過手動執行如下命令安裝依賴外掛

go get -u -v github.com/nsf/gocode
go get -u -v github.com/rogpeppe/godef
go get -u -v github.com/zmb3/gogetdoc
go get -u -v github.com/golang/lint/golint
go get -u -v github.com/lukehoban/go-outline
go get -u -v sourcegraph.com/sqs/goreturns
go get -u -v golang.org/x/tools/cmd/gorename
go get -u -v github.com/tpng/gopkgs
go get -u -v github.com/newhook/go-symbols
go get -u -v golang.org/x/tools/cmd/guru
go get -u -v github.com/cweill/gotests/...

VSCode IDE要支援Go語言開發,執行以下命令安裝Go編譯除錯外掛。

go get -v -u github.com/peterh/liner github.com/derekparker/delve/cmd/dlv
brew install go-delve/delve/delve
go get -v -u github.com/peterh/liner github.com/derekparker/delve/cmd/dlv
Go編譯除錯外掛dlv需要證書的支援,按照以下步驟可以為dlv建立和修改證書
1.開啟“鑰匙串訪問”
2.開啟選單->鑰匙串訪問->證書助理->建立證書

3.設定程式碼證書資訊
 
4.單擊“繼續”,有限期(天數):365,可以自己修改,3650
5.一直繼續,直到看到“指定用於該證書的位置”鑰匙串,選擇“系統”並單擊“建立”按鈕(必須選擇“系統”類別,否則最後重新編譯帶程式碼簽名dlv會失敗)
 
6.重啟Finder,再開啟“鑰匙串訪問”,選擇“系統”,就會看到建立好的“dlv”證書
7.右鍵"dlv"證書,選擇“顯示簡介->信任->程式碼簽名”修改為:始終信任
 
8.開啟terminal,進入到之前安裝好的$GOPATH/src目錄下的dlv原始碼檔案目錄:github.com/derekparker/delve;輸入如下命令就可以重新編譯出一個帶程式碼簽名的dlv執行程式(CERT指定的證書名需要和建立名保持一致)
GO15VENDOREXPERIMENT=1 CERT=dlv make install

最後,退出重新開啟VSCode就可以進行Go程式的開發和除錯了


參考資料

[1]. The Go Programming Language: https://golang.org/project/
[2]. Editor plugins and IDEs: https://golang.org/doc/editors.html
[3]. vscode-go: https://github.com/Microsoft/vscode-go