Files
build-web-application-with-…/zh-tw/01.4.md
2019-02-26 01:40:54 +08:00

637 lines
21 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 1.4 Go開發工具
本節我將介紹幾個開發工具它們都具有自動化提示自動化fmt功能。因為它們都是跨平臺的所以安裝步驟之類別的都是通用的。
## LiteIDE
LiteIDE是一款專門為Go語言開發的跨平臺輕量級整合開發環境IDE由visualfc編寫。
![](images/1.4.liteide.png?raw=true)
圖1.4 LiteIDE主介面
**LiteIDE主要特點**
* 支援主流作業系統
* Windows
* Linux
* MacOS X
* Go編譯環境管理和切換
* 管理和切換多個Go編譯環境
* 支援Go語言交叉編譯
* 與Go標準一致的專案管理方式
* 基於GOPATH的套件瀏覽器
* 基於GOPATH的編譯系統
* 基於GOPATH的Api文件檢索
* Go語言的編輯支援
* 類別瀏覽器和大綱顯示
* Gocode(程式碼自動完成工具)的完美支援
* Go語言文件檢視和Api快速檢索
* 程式碼表達式資訊顯示`F1`
* 原始碼定義跳轉支援`F2`
* Gdb斷點和除錯支援
* gofmt自動格式化支援
* 其他特徵
* 支援多國語言介面顯示
* 完全外掛體系結構
* 支援編輯器配色方案
* 基於Kate的語法顯示支援
* 基於全文的單詞自動完成
* 支援鍵盤快捷鍵繫結方案
* Markdown文件編輯支援
* 即時預覽和同步顯示
* 自訂CSS顯示
* 可匯出HTML和PDF文件
* 批量轉換/合併為HTML/PDF文件
**LiteIDE安裝配置**
* LiteIDE安裝
* 下載地址 <http://sourceforge.net/projects/liteide/files>
* 原始碼地址 <https://github.com/visualfc/liteide>
首先安裝好Go語言環境然後根據作業系統下載LiteIDE對應的壓縮檔案直接解壓即可使用。
* 編譯環境設定
根據自身系統要求切換和配置LiteIDE當前使用的環境變數。
以Windows作業系統64位Go語言為例
工具欄的環境配置中選擇win64`編輯環境`進入LiteIDE編輯win64.env檔案
GOROOT=c:\go
GOBIN=
GOARCH=amd64
GOOS=windows
CGO_ENABLED=1
PATH=%GOBIN%;%GOROOT%\bin;%PATH%
。。。
將其中的`GOROOT=c:\go`修改為當前Go安裝路徑存檔即可如果有MinGW64可以將`c:\MinGW64\bin`加入PATH中以便go呼叫gcc支援CGO編譯。
以Linux作業系統64位Go語言為例
工具欄的環境配置中選擇linux64`編輯環境`進入LiteIDE編輯linux64.env檔案
GOROOT=$HOME/go
GOBIN=
GOARCH=amd64
GOOS=linux
CGO_ENABLED=1
PATH=$GOBIN:$GOROOT/bin:$PATH
。。。
將其中的`GOROOT=$HOME/go`修改為當前Go安裝路徑存檔即可。
* GOPATH設定
Go語言的工具鏈使用GOPATH設定是Go語言開發的專案路徑列表在命令列中輸入(在LiteIDE中也可以`Ctrl+,`直接輸入)`go help gopath`快速檢視GOPATH文件。
在LiteIDE中可以方便的檢視和設定GOPATH。透過`選單檢視GOPATH`設定可以檢視系統中已存在的GOPATH列表
同時可根據需要新增專案目錄到自訂GOPATH列表中。
## Sublime Text
這裡將介紹Sublime Text 3以下簡稱Sublime+ GoSublime + gocode的組合那麼為什麼選擇這個組合呢
- 自動化提示程式碼,如下圖所示
![](images/1.4.sublime1.png?raw=true)
圖1.5 sublime自動化提示介面
- 儲存的時候自動格式化程式碼讓您編寫的程式碼更加美觀符合Go的標準。
- 支援專案管理
![](images/1.4.sublime2.png?raw=true)
圖1.6 sublime專案管理介面
- 支援語法高亮
- Sublime Text 3可免費使用只是儲存次數達到一定數量之後就會提示是否購買點選取消繼續用和正式註冊版本沒有任何區別。
接下來就開始講如何安裝,下載 [Sublime](http://www.sublimetext.com/)
根據自己相應的系統下載相應的版本然後開啟Sublime對於不熟悉Sublime的同學可以先看一下這篇文章[Sublime Text 全程指南](http://blog.jobbole.com/88648/)或者[sublime text3入門課程](http://blog.csdn.net/sam976/article/details/52076271)
1. 開啟之後安裝 Package ControlCtrl+` 開啟命令列,執行如下程式碼:
適用於 Sublime Text 3
```Go
import urllib.request,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();urllib.request.install_opener(urllib.request.build_opener(urllib.request.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib.request.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read())
```
適用於 Sublime Text 2
```Go
import urllib2,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();os.makedirs(ipp)ifnotos.path.exists(ipp)elseNone;urllib2.install_opener(urllib2.build_opener(urllib2.ProxyHandler()));open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read());print('Please restart Sublime Text to finish installation')
```
這個時候重啟一下Sublime可以發現在在選單欄多了一個如下的節目說明Package Control已經安裝成功了。
![](images/1.4.sublime3.png?raw=true)
圖1.7 sublime套件管理
2. 安裝完之後就可以安裝Sublime的外掛了。需安裝GoSublime、SidebarEnhancements和Go Build安裝外掛之後記得重啟Sublime生效Ctrl+Shift+p開啟Package Controll 輸入`pcip`即“Package Control: Install Package”的縮寫
這個時候看左下角顯示正在讀取套件資料,完成之後出現如下介面
![](images/1.4.sublime4.png?raw=true)
圖1.8 sublime安裝外掛介面
這個時候輸入GoSublime按確定就開始安裝了。同理應用於SidebarEnhancements和Go Build。
3. 安裝 [gocode](https://github.com/nsf/gocode/)
go get -u github.com/nsf/gocode
gocode 將會安裝在預設`$GOBIN`
另外建議安裝gotests(產生測試程式碼):
先在sublime安裝gotests外掛,再執行:
```Go
go get -u -v github.com/cweill/gotests/...
```
3. 驗證是否安裝成功你可以開啟Sublime開啟main.go看看語法是不是高亮了輸入`import`是不是自動化提示了,`import "fmt"`之後,輸入`fmt.`是不是自動化提示有函數了。
如果已經出現這個提示,那說明你已經安裝完成了,並且完成了自動提示。
如果沒有出現這樣的提示,一般就是你的`$PATH`沒有配置正確。你可以開啟終端輸入gocode是不是能夠正確執行如果不行就說明`$PATH`沒有配置正確。
(針對XP)有時候在終端能執行成功,但sublime無提示或者編譯解碼錯誤,請安裝sublime text3和convert utf8外掛試一試
4. MacOS下已經設定了$GOROOT, $GOPATH, $GOBIN還是沒有自動提示怎麼辦。
請在sublime中使用command + 9 然後輸入env檢查$PATH, GOROOT, $GOPATH, $GOBIN等變數 如果沒有請採用下面的方法。
首先建立下面的連線, 然後從Terminal中直接啟動sublime
ln -s /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/local/bin/sublime
## Visual Studio Code
vscode是微軟基於Electron和web技術建構的開源編輯器, 是一款很強大的編輯器。開源地址:https://github.com/Microsoft/vscode
1、安裝Visual Studio Code 最新版
官方網站https://code.visualstudio.com/
下載Visual Studio Code 最新版,安裝過程略。
2、安裝Go外掛
點選右邊的 Extensions 圖示
搜尋Go外掛
在外掛列表中,選擇 Go進行安裝安裝之後系統會提示重啟 Visual Studio Code。
建議把自動儲存功能開啟。開啟方法為:選擇選單 File點選 Auto save。
vscode程式碼設定可用於Go擴充套件。這些都可以在使用者的喜好來設定或工作區設定.vscode/settings.json
開啟首選項-使用者設定 settings.json:
```Go
{
"go.buildOnSave": true,
"go.lintOnSave": true,
"go.vetOnSave": true,
"go.buildFlags": [],
"go.lintFlags": [],
"go.vetFlags": [],
"go.coverOnSave": false,
"go.useCodeSnippetsOnFunctionSuggest": false,
"go.formatOnSave": true,
//goimports
"go.formatTool": "goreturns",
"go.goroot": "",//你的Goroot
"go.gopath": "",//你的Gopath
}
```
接著安裝相依套件支援(網路不穩定,請直接到 Github [Golang](https://github.com/golang) 下載再移動到相關目錄):
```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 還有一項很強大的功能就是斷點除錯,結合 [delve](https://github.com/derekparker/delve) 可以很好的進行 Go 程式碼除錯
```Go
go get -v -u github.com/peterh/liner github.com/derekparker/delve/cmd/dlv
brew install go-delve/delve/delve(mac可選)
```
如果有問題再來一遍:
```Go
go get -v -u github.com/peterh/liner github.com/derekparker/delve/cmd/dlv
```
注意:修改"dlv-cert"證書, 選擇"顯示簡介"->"信任"->"程式碼簽名" 修改為: 始終信任
開啟首選項-工作區設定,配置launch.json:
```Go
{
"version": "0.2.0",
"configurations": [
{
"name": "main.go",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"program": "${workspaceRoot}",//工作空間路徑
"env": {},
"args": [],
"showLog": true
}
]
}
```
## Atom
Atom是Github基於Electron和web技術建構的開源編輯器, 是一款很漂亮強大的編輯器缺點是速度比較慢。
首先要先安裝下Atom下載地址: https://atom.io/
然後安裝go-plus外掛:
go-plus是Atom上面的一款開源的go語言開發環境的的外掛
它需要依賴下面的go語言工具:
```Go
1.autocomplete-go gocode的程式碼自動提示
2.gofmt 使用goftm,goimports,goturns
3.builder-go:go-install 和go-test,驗證程式碼給出建議
4.gometalinet-linter:goline,vet,gotype的檢查
5.navigator-godef:godef
6.tester-goo :go test
7.gorename :rename
```
在Atom中的 Preference 中可以找到install選單,輸入 go-plus,然後點選安裝(install)
就會開始安裝 go-plus go-plus 外掛會自動安裝對應的依賴外掛如果沒有安裝對應的go的類別函式庫會自動執行: go get 安裝。
## GoLand
GoLand 是 JetBrains 公司推出的 Go 語言整合開發環境,是 Idea Go 外掛的強化版。GoLand 同樣基於 IntelliJ 平臺開發,支援 JetBrains 的外掛體系。
下載地址: https://www.jetbrains.com/go/
## Vim
Vim是從vi發展出來的一個文字編輯器, 程式碼自動完成、編譯及錯誤跳轉等方便程式設計的功能特別豐富,在程式設計師中被廣泛使用。
vim-go是vim上面的一款開源的go語言使用最為廣泛開發環境的的外掛
外掛地址:[github.com/fatih/vim-go](https://github.com/fatih/vim-go)
vim的外掛管理主要有[Pathogen](https://github.com/tpope/vim-pathogen)與[Vundle](https://github.com/VundleVim/Vundle.vim)
,但是其作用的方面不同。
pathogen是為了解決每一個外掛安裝後文件分散到多個目錄不好管理而存在的。vundle是為了解決自動搜尋及下載外掛而存在的。
這兩個外掛可同時使用。
1.安裝Vundle
```sh
mkdir ~/.vim/bundle
git clone https://github.com/gmarik/Vundle.vim.git ~/.vim/bundle/Vundle.vim
```
修改.vimrc將Vundle的相關配置置在最開始處([詳細參考Vundle的介紹文件](https://github.com/VundleVim/Vundle.vim))
```sh
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
" All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required
```
2.安裝Vim-go
修改~/.vimrc在vundle#begin和vundle#end間增加一行
```sh
Plugin 'fatih/vim-go'
```
在Vim內執行: PluginInstall
3.安裝YCM(Your Complete Me)進行自動自動完成
在~/.vimrc中新增一行
```sh
Plugin 'Valloric/YouCompleteMe'
```
在Vim內執行: PluginInstall
![](images/1.4.vim.png?raw=true)
圖1.9 VIM編輯器自動化提示Go介面
接著我們繼續配置vim:
1. 配置vim高亮顯示
cp -r $GOROOT/misc/vim/* ~/.vim/
2. 在~/.vimrc檔案中增加語法高亮顯示
filetype plugin indent on
syntax on
3. 安裝[Gocode](https://github.com/nsf/gocode/)
go get -u github.com/nsf/gocode
gocode預設安裝到`$GOPATH/bin`下面。
4. 配置[Gocode](https://github.com/nsf/gocode/)
~ cd $GOPATH/src/github.com/nsf/gocode/vim
~ ./update.bash
~ gocode set propose-builtins true
propose-builtins true
~ gocode set lib-path "/home/border/gocode/pkg/linux_amd64"
lib-path "/home/border/gocode/pkg/linux_amd64"
~ gocode set
propose-builtins true
lib-path "/home/border/gocode/pkg/linux_amd64"
>gocode set裡面的兩個引數的含意說明
>
>propose-builtins是否自動提示Go的內建函式、型別和常量預設為false不提示。
>
>lib-path:預設情況下gocode只會搜尋**$GOPATH/pkg/$GOOS_$GOARCH** 和 **$GOROOT/pkg/$GOOS_$GOARCH**目錄下的套件當然這個設定就是可以設定我們額外的lib能訪問的路徑
5. 恭喜你,安裝完成,你現在可以使用`:e main.go`體驗一下開發Go的樂趣。
更多VIM 設定, 可參考[連結](http://www.cnblogs.com/witcxc/archive/2011/12/28/2304704.html)
## Emacs
Emacs傳說中的神器她不僅僅是一個編輯器它是一個整合環境或可稱它為整合開發環境這些功能如讓使用者置身於全功能的作業系統中。
![](images/1.4.emacs.png?raw=true)
圖1.10 Emacs編輯Go主介面
1. 配置Emacs高亮顯示
cp $GOROOT/misc/emacs/* ~/.emacs.d/
2. 安裝[Gocode](https://github.com/nsf/gocode/)
go get -u github.com/nsf/gocode
gocode預設安裝到`$GOBIN`裡面下面。
3. 配置[Gocode](https://github.com/nsf/gocode/)
~ cd $GOPATH/src/github.com/nsf/gocode/emacs
~ cp go-autocomplete.el ~/.emacs.d/
~ gocode set propose-builtins true
propose-builtins true
~ gocode set lib-path "/home/border/gocode/pkg/linux_amd64" // 換為你自己的路徑
lib-path "/home/border/gocode/pkg/linux_amd64"
~ gocode set
propose-builtins true
lib-path "/home/border/gocode/pkg/linux_amd64"
4. 需要安裝 [Auto Completion](http://www.emacswiki.org/emacs/AutoComplete)
下載AutoComplete並解壓
~ make install DIR=$HOME/.emacs.d/auto-complete
配置~/.emacs檔案
;;auto-complete
(require 'auto-complete-config)
(add-to-list 'ac-dictionary-directories "~/.emacs.d/auto-complete/ac-dict")
(ac-config-default)
(local-set-key (kbd "M-/") 'semantic-complete-analyze-inline)
(local-set-key "." 'semantic-complete-self-insert)
(local-set-key ">" 'semantic-complete-self-insert)
詳細資訊參考: http://www.emacswiki.org/emacs/AutoComplete
5. 配置.emacs
;; golang mode
(require 'go-mode-load)
(require 'go-autocomplete)
;; speedbar
;; (speedbar 1)
(speedbar-add-supported-extension ".go")
(add-hook
'go-mode-hook
'(lambda ()
;; gocode
(auto-complete-mode 1)
(setq ac-sources '(ac-source-go))
;; Imenu & Speedbar
(setq imenu-generic-expression
'(("type" "^type *\\([^ \t\n\r\f]*\\)" 1)
("func" "^func *\\(.*\\) {" 1)))
(imenu-add-to-menubar "Index")
;; Outline mode
(make-local-variable 'outline-regexp)
(setq outline-regexp "//\\.\\|//[^\r\n\f][^\r\n\f]\\|pack\\|func\\|impo\\|cons\\|var.\\|type\\|\t\t*....")
(outline-minor-mode 1)
(local-set-key "\M-a" 'outline-previous-visible-heading)
(local-set-key "\M-e" 'outline-next-visible-heading)
;; Menu bar
(require 'easymenu)
(defconst go-hooked-menu
'("Go tools"
["Go run buffer" go t]
["Go reformat buffer" go-fmt-buffer t]
["Go check buffer" go-fix-buffer t]))
(easy-menu-define
go-added-menu
(current-local-map)
"Go tools"
go-hooked-menu)
;; Other
(setq show-trailing-whitespace t)
))
;; helper function
(defun go ()
"run current buffer"
(interactive)
(compile (concat "go run " (buffer-file-name))))
;; helper function
(defun go-fmt-buffer ()
"run gofmt on current buffer"
(interactive)
(if buffer-read-only
(progn
(ding)
(message "Buffer is read only"))
(let ((p (line-number-at-pos))
(filename (buffer-file-name))
(old-max-mini-window-height max-mini-window-height))
(show-all)
(if (get-buffer "*Go Reformat Errors*")
(progn
(delete-windows-on "*Go Reformat Errors*")
(kill-buffer "*Go Reformat Errors*")))
(setq max-mini-window-height 1)
(if (= 0 (shell-command-on-region (point-min) (point-max) "gofmt" "*Go Reformat Output*" nil "*Go Reformat Errors*" t))
(progn
(erase-buffer)
(insert-buffer-substring "*Go Reformat Output*")
(goto-char (point-min))
(forward-line (1- p)))
(with-current-buffer "*Go Reformat Errors*"
(progn
(goto-char (point-min))
(while (re-search-forward "<standard input>" nil t)
(replace-match filename))
(goto-char (point-min))
(compilation-mode))))
(setq max-mini-window-height old-max-mini-window-height)
(delete-windows-on "*Go Reformat Output*")
(kill-buffer "*Go Reformat Output*"))))
;; helper function
(defun go-fix-buffer ()
"run gofix on current buffer"
(interactive)
(show-all)
(shell-command-on-region (point-min) (point-max) "go tool fix -diff"))
6. 恭喜你你現在可以體驗在神器中開發Go的樂趣。預設speedbar是關閉的如果開啟需要把 ;; (speedbar 1) 前面的註釋去掉,或者也可以透過 *M-x speedbar* 手動開啟。
## Eclipse
Eclipse也是非常常用的開發利器以下介紹如何使用Eclipse來編寫Go程式。
![](images/1.4.eclipse1.png?raw=true)
圖1.11 Eclipse編輯Go的主介面
1. 首先下載並安裝好[Eclipse](http://www.eclipse.org/)
2. 下載[goclipse](https://code.google.com/p/goclipse/)外掛
http://code.google.com/p/goclipse/wiki/InstallationInstructions
3. 下載gocode用於go的程式碼自動完成提示
gocode的github地址
https://github.com/nsf/gocode
在windows下要安裝git通常用[msysgit](https://code.google.com/p/msysgit/)
再在cmd下安裝
go get -u github.com/nsf/gocode
也可以下載程式碼直接用go build來編譯會產生gocode.exe
4. 下載[MinGW](http://sourceforge.net/projects/mingw/files/MinGW/)並按要求裝好
5. 配置外掛
Windows->Reference->Go
(1).配置Go的編譯器
![](images/1.4.eclipse2.png?raw=true)
圖1.12 設定Go的一些基礎資訊
(2).配置Gocode可選程式碼自動完成設定Gocode路徑為之前產生的gocode.exe檔案
![](images/1.4.eclipse3.png?raw=true)
圖1.13 設定gocode資訊
(3).配置GDB可選做除錯用設定GDB路徑為MingW安裝目錄下的gdb.exe檔案
![](images/1.4.eclipse4.png?raw=true)
圖1.14 設定GDB資訊
6. 測試是否成功
新建一個go工程再建立一個hello.go。如下圖
![](images/1.4.eclipse5.png?raw=true)
圖1.15 新建專案編輯檔案
除錯如下要在console中用輸入命令來除錯
![](images/1.4.eclipse6.png?raw=true)
圖1.16 除錯Go程式
## IntelliJ IDEA
熟悉Java的讀者應該對於idea不陌生idea是透過一個外掛來支援go語言的高亮語法,程式碼提示和重構實現。
1. 先下載ideaidea支援多平臺win,mac,linux如果有錢就買個正式版如果不行就使用社群免費版對於只是開發Go語言來說免費版足夠用了
![](images/1.4.idea1.png?raw=true)
2. 安裝Go外掛點選選單File中的Setting找到Plugins,點選,Broswer repo按鈕。國內的使用者可能會報錯自己解決哈。
![](images/1.4.idea3.png?raw=true)
3. 這時候會看見很多外掛搜尋找到Golang,雙擊,download and install。等到golang那一行後面出現Downloaded標誌後,點OK。
![](images/1.4.idea4.png?raw=true)
然後點 Apply .這時候IDE會要求你重啟。
4. 重啟完畢後,建立新專案會發現已經可以建立golang專案了
![](images/1.4.idea5.png?raw=true)
下一步,會要求你輸入 go sdk的位置,一般都安裝在C:\Golinux和mac根據自己的安裝目錄設定選中目錄確定,就可以了。
## links
* [目錄](<preface.md>)
* 上一節: [Go 命令](<01.3.md>)
* 下一節: [總結](<01.5.md>)