Creating Your Own Package in Go

A package in Go is a namespace that organizes a set of related files. We can think of packages as being similar to different folders. Go standard library comes with a number of packages which can be used for building real-world applications. Moreover Go supports writing our own packages promoting code modularization and better composability of applications following certain rules, like all source files within the package must declare the same package-name. Identifiers, Function and Types will be exported to other packages if the first letter of the identifier name starts with an uppercase letter.

In post Creating HTTP Server in Go we already updated Path with GOROOT, GOPATH and GOBIN, so as part of this post we will simply start with creating a package in Go following below steps:

Step 1: Create a directory inside your workspace to keep source code of a package, for me it’s numberutil under $GOPATH/github.com/arpitaggarwal:

$ mkdir -p $GOPATH/github.com/arpitaggarwal/numberutil

Step 2: Move to directory we created in previous step and create a file named decimalTobinary.go inside it, as follows:

$ cd $GOPATH/github.com/arpitaggarwal/numberutil
$ touch decimalTobinary.go

Copy following Go code:

package numberutil

import "strconv"

//Convert Decimal to Binary
func DecimalToBinary(decimal int64) string {
	binary := strconv.FormatInt(decimal, 2)
	return binary
}

Above code contains a single go function which takes Decimal number as input and convert it to Binary using strconv.FormatInt function.

Step 3: Build numberutil package using go tool, as follows:

$ cd $GOPATH
$ go build github.com/arpitaggarwal/numberutil

Step 4: Next we will create number-util.go with a main() method to use DecimalToBinary function from numberutil package we created, as follows:

$ cd $GOPATH/github.com/arpitaggarwal/
$ touch number-util.go

Copy following Go code:

package main

import (
	"fmt"
	"github.com/arpitaggarwal/numberutil"
)

func main() {
	i23 := int64(23)
	fmt.Printf("Decimal to Binary for 23 is %s \n", numberutil.DecimalToBinary(i23))
}

Step 5: Install number-util.go using go tool:

$ go install $GOPATH/github.com/arpitaggarwal/number-util.go

Above command compile number-util.go and generate executable binary file of it in $GOROOT/bin or $GOBIN directory.

Step 6: Run number-util.go moving to golang directory:

$ cd golang
$ ./go/bin/number-util

Step 7: Now we will generate documentation of numberutil package we created which is as simple as running godoc tool with -http flag for the port number from the terminal, as follows:

godoc -http=:9999

Now, opening http://localhost:9999/pkg/github.com/arpitaggarwal/numberutil/ in browser will show us the documentation of numberutil package we have created.

Go also support using third party libraries or packages by installing them using go get command or copying it manually to $GOPATH/src or $GOPATH for example, If we want to use Reverse function from “github.com/golang/example/stringutil” package which is not available by default in go standard library then we can install it as:

$ cd golang
$ go get github.com/golang/example/stringutil

Or clone the package and copy it to $GOPATH/src or $GOPATH directory, then use it as:


package main

import (
	"fmt"
	"github.com/golang/example/stringutil"
)
func main() {
	fmt.Println(stringutil.Reverse("!olleh"))
}

Complete source code is hosted on github.

Advertisements

Creating HTTP Server in Go

In this post, we will create a simple HTTP server in Go following some simple steps. Before starting, let me give you a brief introduction about Go.

What is Go?

Go is an open source programming language which is case sensitive and statically-typed with syntax similar to that of C language created at Google in 2007. It compiles very quickly, supports concurrency at the language level and provides garbage collection, type safety, dynamic-typing capability, many advanced built-in types such as variable length arrays and key-value maps though there is no support for generic programming, type inheritance, method or operator overloading, pointer arithmetic and assertions.

Now, let’s start with setting up the environment to run our first HTTP Server, following below steps:

Step 1: Download and extract Go in any directory, for me it’s golang under directory /Users/ArpitAggarwal/ as follows:


$ mkdir golang
$ cd golang
$ wget https://storage.googleapis.com/golang/go1.8.3.darwin-amd64.tar.gz
$ tar -xvzf go1.8.3.darwin-amd64.tar.gz

Step 2: Update Path with GOROOT, GOPATH and GOBIN, as follows:

$ export GOROOT=/Users/ArpitAggarwal/golang/go
$ export GOPATH=$GOROOT/src
$ export GOBIN=$GOROOT/bin
$ export PATH=$PATH:$GOPATH:$GOBIN

GOROOT refers to the go installation directory.
GOPATH refers to our go workspace directory or where go build is done.
GOBIN refers to the directory where go generate executable binaries.

Step 3: Verify if GOPATH is set properly on Bash, executing following command:

$ env | grep -E "^GO"

Step 4: Create a directory inside workspace to keep source code:

$ mkdir -p $GOPATH/github.com/arpitaggarwal

Step 5: Move to directory we created in previous step and create a file named webserver.go inside it, as follows:

$ cd $GOPATH/github.com/arpitaggarwal
$ touch webserver.go

Copy following Go code:

package main

import (
	"fmt"
	"log"
	"net/http"
)

func helloWorld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World!") // send data to client side
}

func main() {
	http.HandleFunc("/", helloWorld)         // set router
	err := http.ListenAndServe(":8080", nil) // set listen port
	if err != nil {
		log.Fatal("Error while starting GO http server on port - 8080 : ", err) //log error and exit in case of error at server boot up
	}
}

Let’s understand what does each line mean.

package main – It defines the package name of the program.

import (“fmt”, “log” “net/http”) – is a preprocessor command which tells the Go compiler to include all files from fmt, log and net/http package.

func helloWorld(w http.ResponseWriter, r *http.Request) – is a go function.

main() – is the main function where the program execution begins.

Step 6: Install webserver.go using go tool, as follows:


$ go install $GOPATH/github.com/arpitaggarwal/webserver.go

Above command compile webserver.go and generate executable binary file of it in $GOROOT/bin or GOBIN.

Step 7: Run webserver moving to golang directory, as follows:


$ cd golang
$ ./go/bin/webserver

Now, opening http://localhost:8080/ in browser or executing command:

curl http://localhost:8080

will show us “Hello World!” as response.

Step 8: Optionally we can run binary file in background using nohup command, as follows:


$ cd golang
$ nohup ./go/bin/webserver &;

Complete source code is hosted on github.