14 KiB
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
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, encontreLiteEnve na lista esquerda, abro o arquivowin64.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:\gopara o caminho de instalação configurado anteriormente, salve o arquivo. Para ter suporte completo aocgo, você precisar ter instalado o MinGW64 e deve adicionarc:\MinGW64\bina 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, encontreLiteEnvno menu a esquerda e abra o arquivolinux64.env. Edite-o conforme segue.GOROOT=$HOME/go GOBIN= GOARCH=amd64 GOOS=linux CGO_ENABLED=1 PATH=$GOBIN:$GOROOT/bin:$PATH 。。。Substitua
GOROOT=$HOME/gopara 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 digitego help gopathpara maiores detalhes. É bastante fácil visualizar e alterar a variável $GOPATH no LiteIDE. Use o menuView - Setup GOPATHpara 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 suitable for your operating system.
-
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 Controloption in the "Preferences" menu.Figure 1.7 Sublime Package Control
-
To install GoSublime, SidebarEnhancements and Go Build, press
Ctrl+Shift+pto open Package Control, then typepcip(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.
-
To verify that the installation is successful, open Sublime, then open the
main.gofile to see if it has the proper syntax highlighting. Typeimportto see if code completion prompts appear. After typingimport "fmt", typefmt.anywhere after theimportdeclaration 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
-
Syntax highlighting for Go
cp -r $GOROOT/misc/vim/* ~/.vim/ -
Enabling syntax highlighting
filetype plugin indent on syntax on -
Install gocode
go get -u github.com/nsf/gocodegocode will be installed in
$GOBINas default -
Configure 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_$GOARCHand$GOROOT/pkg/$GOOS_$GOARCH. This setting can be used to add additional paths. -
Congratulations! Try
:e main.goto 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
-
Syntax highlighting
cp $GOROOT/misc/emacs/* ~/.emacs.d/ -
Install gocode
go get -u github.com/nsf/gocodegocode will be installed in
$GOBINas default -
Configure 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" -
Install Auto Completion Download and uncompress
~ make install DIR=$HOME/.emacs.d/auto-completeConfigure ~/.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 for more details.
-
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")) -
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 throughM-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
-
Download and install Eclipse
-
Download goclipse http://code.google.com/p/goclipse/wiki/InstallationInstructions
-
Download gocode
gocode in Github.
https://github.com/nsf/gocodeYou need to install git in Windows, usually we use msysgit
Install gocode in the command tool
go get -u github.com/nsf/gocodeYou can install from source code if you like.
-
Download and install MinGW
-
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
-
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.
-
Download IDEA, there is no difference between the Ultimate and Community editions
-
Install the Go plugin. Choose
File - Setting - Plugins, then clickBrowser repo. -
Search
golang, double clickdownload and installand wait for the download to complete.Click
Apply, then restart. -
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 for setup and use IntelliJ IDEA with Go step by step *** )
Links
- Directory
- Previous section: Go commands
- Next section: Summary
















