Thursday, June 18, 2015

Intro to Go Programming Package Creation

Go tools requires code organization in specific way for easy build, deploy your go code. The following section describes the process.

1) Create a specific directory $HOME/mygo
2) Set the environment variable GOPATH=$HOME/mygo
3) Create a unique namespace mkdir $GOPATH/src/github.com/nf

Develop your code inside the namespace

mkdir $GOPATH/src/github.com/nf/hello
cd $GOPATH/src/github.com/nf/hello
>> write your hello.go

build and install your hello.go with go install command in the current directory the binary will be installed in $GOPATH/bin directory

Lets create our own package to by used by other go program such as hello.go

mkdir $GOPATH/src/github.com/nf/string
cd $GOPATH/src/github.com/nf/string/string.go
>> write your string.go

================
package string

func Reverse(s string) string {
        b := []byte(s)
        for i:=0; i < len(s)/2; i++ {
                j := len(s)-i-1
                ch := b[i]
                b[i] = b[j]
                b[j] = ch
        }
        return (string(b))

}
===============
run go install in the string directory to create package string the output string.a will appear in 
$GOPATH/pkg/linux_amd64/github.com/nf/string.a 

Now lets use our string package in our hello.go

cd $GOPATH/src/github.com/nf/hello.go

===============
package main

import (
        "fmt"
        "github.com/nf/string"
)

func main() {
        fmt.Println(string.Reverse("Hello World!!"))
}
================

build the hello.go with go install

Cool!!

Let's write test program to test the package
cd $GOPATH/src/github.com/nf/string/
vi string_test.go


======================
package string

import "testing"

func Test(t *testing.T) {
        var tests = []struct {
                s, want string
        } {
                {"Backward", "drawkcaB"},
                {"Hello, # %", "% # ,olleH"},
                {"", ""},
        }

        for _, c:= range tests {
                got := Reverse(c.s)
                if got != c.want {
                        t.Errorf("Reverse(%q) == %q, want %q", c.s, got, c.want)
                }
        }

}

===============

run go test (If no error great, else fix the issue)