Nov 29, 2013

Getting started with a "virtual" Go environment

Given how easy it is to write highly concurrent code in Go (aka "golang"), it is probably worth learning this language. Personally, I believe Go is not yet mature enough for "production" projects other than servers maybe (and I am sure there are people who will not agree with my belief...). But for doing science, juggling huge ammounts of data (no, I will not say the "B"-word...), and your typical scripting pipelines, Go is really great. On top of that, Go is easy to learn because it has a simple syntax and a very "bare bones" approach in so many aspects. So if you feel like giving it a try, here is a quick recipe to bootstrap a Go development environment within moments:

First, install Go itself using your package manager; For example, on OSX, you might use Homebrew, and on Ubuntu or Debian you'd probably use apt:

brew install go --cross-compile-common
apt-get install golang

Notice that if you are on a LTS version of Ubuntu (Precise/12.04 right now) or Debian, you might actually want to install a more up-to-date binary. Next, you need to set the global environment variable GOROOT. It has to point to the directory you installed Go in; When using Homebrew on OSX, this can be tricky, so here is a snippet that will create the correct path for you:

export GOROOT=$(brew --prefix)/Cellar/go/$(go \
version | cut -f3 -d' ' | sed 's/go//')/libexec

Protip: If during the next steps you see a lot of errors of the form:

imports PKGNAME: unrecognized import path "PATH"

They probably occur while running go get SOME_PKG, and it most likely just means that your GOROOT is wrong or unset. Finally, you want to quickly bootstrap a "virtual" development environment for Go. For this, I use a simple shell script (that I call goinit) to set up the directory structure and an "activate-able" environment [UPDATE 2013-12-17: additional go get package lines that are extremely useful for development]:


# setup a directory structure for programming in go
PROJECT=`basename "$1"`

mkdir -p "$1"
cd "$1"
mkdir -p "src/$VCS_HUB/$PROJECT"
mkdir bin
mkdir pkg
go get
go get
go get
go get
cat << ACTIVATE > bin/activate
export GOPATH="`pwd`"
export PATH="\$GOPATH/bin:\$PATH"
export PS1="($PROJECT)\$PS1"

Put this script somewhere on you PATH, replace with your own GitHub username (or any other version control system you use), make it executable (chmod 755 goinit), and ensure you have the GOROOT set in your environment and goinit on your path. For example, let's assume you want to start with the Go Tour to learn about the language itself (highly recommendable!); With this setup, bootstrapping your next Go project (simply called "project" here) now is as simple as:

goinit path/to/project
cd path/to/project
source bin/activate

# if you are new to Go, you might want to try this:
go get

The gotour should have opened in your browser. Happy Go coding!

Next → Page 1 of 21