In this post, we will see how we can create REST API with Google Go.
Go
Go is an open source programming language by Google that makes it easy to build simple, reliable, and efficient software.
Learn more about Go
Setting up Go on Ubuntu
I am using Ubuntu for my development environment, so I will explain how to setup Go on Ubuntu.
Here are the steps:
- Download Go from this linkĀ Go Downloads. The current version at this time was 1.11 which could be different when you download it.
- Extract the archive in /usr/local directory
sudo tar -zxvf go1.11.linux-amd64.tar.gz -C /usr/local
- Next we will create a directory for our Go projects.
cd ~ mkdir workspace cd workspace mkdir go
- Now, we will set paths for Go language to run from anywhere
nano ~/.profile
- At the end of the file, add the lines:
export GOROOT=/usr/local/go export GOPATH=$HOME/workspace/go export PATH=$PATH:$GOROOT/bin
GOROOT defines the path where Go is installed
GOPATH defines the path where we will put our Go projects
We added Go bin path to $PATH so that we can execute Go commands from any directory. - Reload the profile with the command
source ~/.profile
- Now, Go should be ready. You can check with the commands:
go env go version
Our first Go program
Let us create a simple hello world program. Here are the steps:
- Move to your Go projects directory ($GOPATH)
cd $GOPATH
- Create two directories named src and pkg. All external packages are downloaded in $GOPATH/pkg directory whereas our project source code lives in $GOPATH/src directory.
- Create your project directory inside the src directory:
mkdir firstproject
- Create a new file:
nano hello.go
- Add following code to the file:
package main import "fmt" func main() { fmt.Println("hello world") }
The file we want to run should have the package named main. Packages are similar to packages in Java or Namespace in other programming languages.
fmt is an existing package provided by Go - Save the file and exit. To run this file, execute the command:
go run hello.go
- We can also build hello command to run on its own:
go build hello.go ./hello