Organizing Go Code

To get started writing Go code, it’s best to follow standard Go conventions.

Arranging Golang code

All Go code lives in one workspace, which is different from typical language experience.

Make a place to put your code that’s unique among the Go standard libary and public world. Many people choose their Github account’s signature. For my case, I chose to let it live under my BitBucket account:

mkdir -p $GOPATH/src/bitbucket.org/theandruu/go-public

Package organization

Let’s write a simple executable program which imports library code from a package we write and prints a message to the screen.

Make a new package directory:

cd $GOPATH/src/bitbucket.org/theandruu/go-public
mkdir -p learning/stringutil

Inside that directory, make a new file: hyphenate-spaces.go and insert the content:

// Package stringutil contains utility functions for working with strings.
package stringutil

import "strings"

// HyphenateSpaces replaces all occurances of a space " " with a hyphen "-"
func HyphenateSpaces(s string) string {
    return strings.Replace(s, " ", "-", -1)
}

Now make a new directory to contain the main function to execute this code:

cd $GOPATH/src/bitbucket.org/theandruu/go-public/learning
mkdir hello

And create a new file there named hello.go with the following content:

package main

import (
    "fmt"

    "bitbucket.org/theandruu/go-public/learning/stringutil"
)

func main() {
    fmt.Println(stringutil.HyphenateSpaces("The lazy fox jumped over the brown dog."))
}

Then from that location, run the code!

> cd ~/Code/go-work/src/bitbucket.org/theandruu/go-public/learning/hello
> hello
The-lazy-fox-jumped-over-the-brown-dog.

Notes on packages

Go’s convention is that the package name is the last element of the import path.

This means our package bitbucket.org/theandruu/go-pupblic/learning/stringutil should match the folder name at that location.

◀   Many Happy Returns Testing Go Code   ▶