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:

  1. Download Go from this linkĀ Go Downloads. The current version at this time was 1.11 which could be different when you download it.
  2. Extract the archive in /usr/local directory
    sudo tar -zxvf go1.11.linux-amd64.tar.gz -C /usr/local
  3. Next we will create a directory for our Go projects.
    cd ~
    mkdir workspace
    cd workspace
    mkdir go
  4. Now, we will set paths for Go language to run from anywhere
    nano ~/.profile
  5. 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.

  6. Reload the profile with the command
    source ~/.profile
  7. 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:

  1. Move to your Go projects directory ($GOPATH)
    cd $GOPATH
  2. 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.
  3. Create your project directory inside the src directory:
    mkdir firstproject
  4. Create a new file:
    nano hello.go
  5. 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

  6. Save the file and exit. To run this file, execute the command:
    go run hello.go
  7. We can also build hello command to run on its own:
    go build hello.go
    ./hello