technology from back to front

Using goinstall for your own local code

I am working towards finishing a small project in go and my thoughts have turned to how I will package it up and release the code. The latest release of go has made some changes to goinstall so that code installed by you as a user can be kept separate from the base installation of go.

The first step in using goinstall is to create a directory structure for your local source, packages and binaries. This can be done like this

% cd ~/work
% mkdir -p gocode/src gocode/pkg gocode/bin

You can then create a GOPATH variable:

export GOPATH=~/work/gocode

Now any go projects can be placed in the $GOPATH/src directory and installed locally, you don’t even need to write makefiles.

For example:

% cd ~/work/gocode/src
% mkdir -p experiment/plutonium

Now create a file experiment.go in the directory:

package plutonium

import (

func ExperimentOne(s string) string {
  return fmt.Sprintf("! DANGER ! %s ! DANGER !", s)

Now this code can be installed locally making it available to your other go projects:

% cd ~/work/gocode/src/experiment/plutonium
% goinstall .
% ls -l ~/work/gocode/pkg/linux_386/experiment
-rw-r--r-- 1 tim tim 9004 Jun 30 13:29 plutonium.a

You can also create executable programs:

% cd ~/work/gocode/src
% mkdir -p experiment/bang
% cd experiment/bang

Create a file called main.go:

package main

import (

func main() {
  log.Print("Running experiment", plutonium.ExperimentOne("Highly dangerous"))
  log.Print("Careful now")

Install and run the program:

% cd ~/work/gocode/src/experiment/bang
% goinstall .
% cd ~/work/gocode/bin
% ./bang
2011/06/30 13:38:45 Running experiment! DANGER ! Highly dangerous ! DANGER !
2011/06/30 13:38:45 Careful now

So no Makefiles are needed! I would still create Makefiles because you will need them if you want to use gotest to run your unit tests.


+ 1 = two

2000-14 LShift Ltd, 1st Floor, Hoxton Point, 6 Rufus Street, London, N1 6PE, UK+44 (0)20 7729 7060   Contact us