404 lines
14 KiB
Markdown
404 lines
14 KiB
Markdown
# Ferramentas de desenvolvimento Go
|
|
|
|
Nesta seção, vamos mostrar alguns IDEs (Integrated Development Environment ou Ambiente de Desenvolvimento Integrado) que podem ajudar você a ser um programador Go mais eficiente, com recursos como auto-complete inteligente e auto-formatação. Todas elas são compatíveis com todos os sitemas operacionais (cross-platform), então os passos descritos abaixo devem ser semelhantes independentemente do sistema que esteja utilizando.
|
|
|
|
## LiteIDE
|
|
|
|
LiteIDE é um IDE leve e de código aberto para desenvolvimento exclusivo de projetos Go. Foi desenvolvido por visualfc.
|
|
|
|

|
|
|
|
Figure 1.4 Painel principal do LiteIDE
|
|
|
|
Recursos do LiteIDE.
|
|
|
|
- Cross-platform
|
|
- Windows
|
|
- Linux
|
|
- Mac OS
|
|
- Cross-compile
|
|
- Gerencimaneto de multiplos ambientes de compilação
|
|
- Suporte a compilação cruzada (cross-compilation) da linguagem Go
|
|
- Gerenciamento do projeto
|
|
- Visão da documentação baseada na variável $GOPATH
|
|
- Sistema de compilação baseado na variável $GOPATH
|
|
- Indíce da documentação da API baseadoo na veriável $GOPATH (N. do T.: Necessita de adaptações melhores para o português)
|
|
- Editor de código fonte Go
|
|
- Alinhamento e identação de código
|
|
- Suporte total ao gocode
|
|
- Visualização da documentação Go e da API
|
|
- Visualização de expressões de código usando `F1`
|
|
- Movimentação entre as funções (Function declaration jump) usando `F2`
|
|
- Suporte ao Gdb (debug)
|
|
- Auto-formatação com `gofmt`
|
|
- Outros
|
|
- Multi-linguagem
|
|
- Sistema de plugins
|
|
- Temas para o editor de textos
|
|
- Suporte a sintaxe baseado no Kate
|
|
- Auto-complete inteligente baseado no texto completo
|
|
- Atalhos customizados
|
|
- Suporte a Markdown
|
|
- Preview em tempo real
|
|
- CSS customizado
|
|
- Exportação para PDF e HTML
|
|
- Conversão para PDF e HTML
|
|
|
|
### Instalação do LiteIDE
|
|
|
|
- Instale o LiteIDE
|
|
- [Página de Download](http://code.google.com/p/golangide)
|
|
- [Código Fonte](https://github.com/visualfc/liteide)
|
|
|
|
Você precisa instalar Go primeiro (conforme a seção 1.1), depois faça o download da versão do LiteIDE mais apropriada para o seu sistema. Apenas descompacte e use diretamente.
|
|
|
|
- Instale o gocode
|
|
|
|
Você precisa instalar o gocode para poder usar o auto-complete inteligente.
|
|
|
|
go get -u github.com/nsf/gocode
|
|
|
|
- Ambiente de compilação
|
|
|
|
Troque a configureguração no LiteIDE para configura-lo corretamente para o seu sistema operacional.
|
|
Por exemplo, no Windows e usando a versão 64-bit da linguagem Go, você deve escolher win64 como ambiente de configuração na barra de ferramentas. Escolha `opinion`, encontre `LiteEnv` e na lista esquerda, abro o arquivo `win64.env`. Ele deve ser parecido como modelo a seguir.
|
|
|
|
GOROOT=c:\go
|
|
GOBIN=
|
|
GOARCH=amd64
|
|
GOOS=windows
|
|
CGO_ENABLED=1
|
|
|
|
PATH=%GOBIN%;%GOROOT%\bin;%PATH%
|
|
。。。
|
|
|
|
Substitua `GOROOT=c:\go` para o caminho de instalação configurado anteriormente, salve o arquivo. Para ter suporte completo ao `cgo`, você precisar ter instalado o MinGW64 e deve adicionar `c:\MinGW64\bin` a a sua variável de ambiente.
|
|
|
|
No Linux, usando uma versão 64-bit da linguagem Go, você deve escolher linux64 como configuração de ambiente na barra de ferramentas. Em seguida, escolha `opinion`, encontre `LiteEnv` no menu a esquerda e abra o arquivo `linux64.env`. Edite-o conforme segue.
|
|
|
|
GOROOT=$HOME/go
|
|
GOBIN=
|
|
GOARCH=amd64
|
|
GOOS=linux
|
|
CGO_ENABLED=1
|
|
|
|
PATH=$GOBIN:$GOROOT/bin:$PATH
|
|
。。。
|
|
|
|
Substitua `GOROOT=$HOME/go` para o caminho da sua instalação, salve o arquivo.
|
|
|
|
- $GOPATH
|
|
|
|
$GOPATH é o caminho do diretório que contém seus projetos Go. Abra a linha de comando (ou apenas use ``Ctrl+` ``no LiteIDE) e então digite `go help gopath` para maiores detalhes.
|
|
É bastante fácil visualizar e alterar a variável $GOPATH no LiteIDE. Use o menu `View - Setup GOPATH` para visualizar e alterar esses valores.
|
|
|
|
## Sublime Text
|
|
|
|
Nesse ponto, iremos introduzir o Sublime Text (ou apenas Sublime) + GoSublime + gocode + MarGo. Vamos lá.
|
|
|
|
- Auto-complete inteligente
|
|
|
|

|
|
|
|
Figure 1.5 Auto-complete inteligente no Sublime
|
|
|
|
- Auto-format source files
|
|
- Project management
|
|
|
|

|
|
|
|
Figure 1.6 Sublime project management
|
|
|
|
- Syntax highlight
|
|
- Free trial forever with no functional limitations. You may be prompted once in a while to remind you to purchase a license, but you can simply ignore it if you wish. Of course, if you do find that it enhances your productivity and you really enjoy using it, please purchase a copy of it and support its continued development!
|
|
|
|
First, download the version of [Sublime](http://www.sublimetext.com/) suitable for your operating system.
|
|
|
|
1. Press ``Ctrl+` ``, open the command tool and input the following commands.
|
|
|
|
import urllib2,os; pf='Package Control.sublime-package'; ipp=sublime.installed_packages_path(); os.makedirs(ipp) if not os.path.exists(ipp) else None; 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'
|
|
|
|
Restart Sublime Text when the installation has finished. You should then find a `Package Control` option in the "Preferences" menu.
|
|
|
|

|
|
|
|
Figure 1.7 Sublime Package Control
|
|
2. To install GoSublime, SidebarEnhancements and Go Build, press `Ctrl+Shift+p` to open Package Control, then type `pcip` (short for "Package Control: Install Package").
|
|
|
|

|
|
|
|
Figure 1.8 Sublime Install Packages
|
|
|
|
Now type in "GoSublime", press OK to install the package, and repeat the same steps for installing SidebarEnhancements and Go Build. Once again, restart the editor when it completes the installation.
|
|
3. To verify that the installation is successful, open Sublime, then open the `main.go` file to see if it has the proper syntax highlighting. Type `import` to see if code completion prompts appear. After typing `import "fmt"`, type `fmt.` anywhere after the `import` declaration to see whether or not intelligent code completion for functions was successfully enabled.
|
|
|
|
If everything is fine, you're all set.
|
|
|
|
If not, check your $PATH again. Open a terminal, type `gocode`. If it does not run, your $PATH was not configured correctly.
|
|
|
|
## Vim
|
|
|
|
Vim is a popular text editor for programmers, which evolved from its slimmer predecessor, Vi. It has functions for intelligent completion, compilation and jumping to errors.
|
|
|
|

|
|
|
|
Figure 1.8 Vim intelligent completion for Go
|
|
|
|
1. Syntax highlighting for Go
|
|
|
|
cp -r $GOROOT/misc/vim/* ~/.vim/
|
|
|
|
2. Enabling syntax highlighting
|
|
|
|
filetype plugin indent on
|
|
syntax on
|
|
|
|
3. Install [gocode](https://github.com/nsf/gocode/)
|
|
|
|
go get -u github.com/nsf/gocode
|
|
|
|
gocode will be installed in `$GOBIN` as default
|
|
|
|
4. Configure [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"
|
|
|
|
Explanation of gocode configuration:
|
|
|
|
propose-builtins: specifies whether or not to open intelligent completion; false by default.
|
|
lib-path: gocode only searches for packages in `$GOPATH/pkg/$GOOS_$GOARCH` and `$GOROOT/pkg/$GOOS_$GOARCH`. This setting can be used to add additional paths.
|
|
|
|
5. Congratulations! Try `:e main.go` to experience the world of Go!
|
|
|
|
## Emacs
|
|
|
|
Emacs is the so-called Weapon of God. She is not only an editor, but also a powerful IDE.
|
|
|
|

|
|
|
|
Figure 1.10 Emacs main panel of Go editor
|
|
|
|
1. Syntax highlighting
|
|
|
|
cp $GOROOT/misc/emacs/* ~/.emacs.d/
|
|
|
|
2. Install [gocode](https://github.com/nsf/gocode/)
|
|
|
|
go get -u github.com/nsf/gocode
|
|
|
|
gocode will be installed in `$GOBIN` as default
|
|
3. Configure [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"
|
|
|
|
4. Install [Auto Completion](http://www.emacswiki.org/emacs/AutoComplete)
|
|
Download and uncompress
|
|
|
|
~ make install DIR=$HOME/.emacs.d/auto-complete
|
|
|
|
Configure ~/.emacs file
|
|
|
|
;;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)
|
|
|
|
Follow this [link](http://www.emacswiki.org/emacs/AutoComplete) for more details.
|
|
5. Configure .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. Congratulations, you're done! Speedbar is closed by default -remove the comment symbols in the line `;;(speedbar 1)` to enable this feature, or you can use it through `M-x speedbar`.
|
|
|
|
## Eclipse
|
|
|
|
Eclipse is also a great development tool. I'll show you how to use it to write Go programs.
|
|
|
|

|
|
|
|
Figure 1.1 Eclipse main panel for editing Go
|
|
|
|
1. Download and install [Eclipse](http://www.eclipse.org/)
|
|
2. Download [goclipse](https://code.google.com/p/goclipse/)
|
|
[http://code.google.com/p/goclipse/wiki/InstallationInstructions](http://code.google.com/p/goclipse/wiki/InstallationInstructions)
|
|
3. Download gocode
|
|
|
|
gocode in Github.
|
|
|
|
https://github.com/nsf/gocode
|
|
|
|
You need to install git in Windows, usually we use [msysgit](https://code.google.com/p/msysgit/)
|
|
|
|
Install gocode in the command tool
|
|
|
|
go get -u github.com/nsf/gocode
|
|
|
|
You can install from source code if you like.
|
|
4. Download and install [MinGW](http://sourceforge.net/projects/mingw/files/MinGW/)
|
|
5. Configure plugins.
|
|
|
|
Windows->Preferences->Go
|
|
|
|
(1).Configure Go compiler
|
|
|
|

|
|
|
|
Figure 1.12 Go Setting in Eclipse
|
|
|
|
(2).Configure gocode(optional), set gocode path to where the gocode.exe is.
|
|
|
|

|
|
|
|
Figure 1.13 gocode Setting
|
|
|
|
(3).Configure gdb(optional), set gdb path to where the gdb.exe is.
|
|
|
|

|
|
|
|
Figure 1.14 gdb Setting
|
|
6. Check the installation
|
|
|
|
Create a new Go project and hello.go file as following.
|
|
|
|

|
|
|
|
Figure 1.15 Create a new project and file
|
|
|
|
Test installation as follows.(you need to type command in console in Eclipse)
|
|
|
|

|
|
|
|
Figure 1.16 Test Go program in Eclipse
|
|
|
|
## IntelliJ IDEA
|
|
|
|
People who have worked with Java should be familiar with this IDE. It supports Go syntax highlighting and intelligent code completion, implemented by a plugin.
|
|
|
|
1. Download IDEA, there is no difference between the Ultimate and Community editions
|
|
|
|

|
|
|
|
2. Install the Go plugin. Choose `File - Setting - Plugins`, then click `Browser repo`.
|
|
|
|

|
|
|
|
3. Search `golang`, double click `download and install` and wait for the download to complete.
|
|
|
|

|
|
|
|
Click `Apply`, then restart.
|
|
4. Now you can create a Go project.
|
|
|
|

|
|
|
|
Input the position of your Go sdk in the next step -basically it's your $GOROOT.
|
|
|
|
( ***See a [blog post](http://wuwen.org/tips-about-using-intellij-idea-and-go/) for setup and use IntelliJ IDEA with Go step by step *** )
|
|
|
|
## Links
|
|
|
|
- [Directory](preface.md)
|
|
- Previous section: [Go commands](01.3.md)
|
|
- Next section: [Summary](01.5.md)
|