Vinay Kumar

Building custom package in Golang

First thing to understand is that golang favors workspace and the golang packages will reside in the workspace. Workspace is the directory defined by GOPATH variable. You can read more on setting up of GOPATH from here. By visiting the workspace you will be able to find two folders named src and bin.

Before moving forward let us try to understand what happens when you install the official golang tour package by using

go get golang.org/x/tour

Now in GOPATH src folder there will be new folder golang.org and inside golang.org folder there will be x folder and inside it there will be tour folder. If observed carefully we can find a pattern in folder structure from the url(golang.org/x/tour). Now lets assume there is a user having github handle as johndoe and package name as myfirstpackage. After running

go get github.com/johndoe/myfirstpackage

In GOPATH src directory github.com folder will be created (if not present) then inside it johndoe folder and inside it myfirstpackage folder will be created. Also in GOPATH bin directory executable file myfirstpackage will be present.

Now following the src directory structure let's create custom package. Let's assume the github handle johndoe and package name samplecustompackage. Create the folder github.com/johndoe/samplecustompackage in GOPATH src directory. For next step create 2 files named main.go and helper/fmt_helper.go with the below contents.

By executing the command go run main.go, Hello will be the output.

To publish the package on github, initialize a public repository and push the changes. After publishing anyone can make use of the package by running

go get github.com/johndoe/samplecustompackage

and executing the binary file bin/samplecustompackage found in GOPATH directory will yield Hello as output.