Build Rest API in Go

Dec 15, 2021by, Akhil C K

Design

Technology

Have you heard that Go is amazing?!

No..? Come, let’s play with Go, this is the time to realize it ?

In the following section, we will learn to install the Go and write the hello world example and moving towards the end we will learn to develop a simple functional API in Go for employee management application that provides CRUD operations.

Let’s jump in and get started.

Setup

We could see the detailed description of the installation here.  Although, we will discuss it here in short. If you are using a Mac and Homebrew is installed on it,  run the code below to install go.

> $brew update

> $brew install golang

After installation, we can verify it by typing in the terminal

> $go

If this lists the go commands and help topic in the terminal, Yes.. we have just installed it and we are on track.

Now let’s build the HelloWorld example.

In mac go workspace should be at $HOME/go and we can change this by $GOPATH environment variable. For now, let’s keep the $HOME/go location for the workspace. Undergo directory create a directory called src and inside that create our project directory, ie “employee-management”. So our workspace looks like,

go
       src
             employee-management

Inside employee management we are going to create our main.go file as follows.

package  main

Import "fmt"

func main(){

fmt.Println("Hello World!")

}

Before we add the entire program, let’s run the main.go file by typing go run main.go in the terminal

> $go run  main.go
"Hello World!"

Cool! We have built a Hello world program in go. Let’s move to the next steps.

Dependencies

We are going to implement the API using the go framework gorilla/mux.

To install this, go to workspace and run the command shown below.

> $go get github.com/gorilla/mux 

Well…We have installed it!.

Go to your workspace. You would be able to see the packages under the pkg directory.

Routes

Next, we are going to implement the APIs. We need APIs for

  • Create employee  – POST /employees
  • List employee       – GET  /employees
  • Get employee       – GET  /employees/{id}
  • Update employee – PUT  /employees/{id}
  • Delete employee  – DELETE  /employees/{id}

Go to our main.go file and create routes like below.

package main

import (

  "log"

  "net/http"

  "github.com/gorilla/mux"

)
func main() {

  r := mux.NewRouter()

  r.HandleFunc("/employees", ListEmployees).Methods("GET")

  r.HandleFunc("/employees", CreateEmployee).Methods("POST")

  r.HandleFunc("/employees/{id}", UpdateEmployee).Methods("PUT")

  r.HandleFunc("/employees/{id}", DeleteEmployee).Methods("DELETE")

  r.HandleFunc("/employees/{id}", GetEmployee).Methods("GET")

  if err := http.ListenAndServe(":3000", r); err != nil {

     log.Fatal(err)

  }

}

We have created routes and it will handle the functions ListEmployees, CreateEmployee, UpdateEmployee, etc, then expose the server on port 3000.

Now we are going to create the employee model using the struct keyword.

package models

type Employee struct {

  ID          string        `json:"id,omitempty"`

  Name        string        `json:"name,omitempty"`

  Designation string        `json:"designation,omitempty"`

}

Next, we have to define the methods for routes that we have already declared.

func CreateEmployee(w http.ResponseWriter, r *http.Request) {

  var employee Employee

_ = json.NewDecoder(r.Body).Decode(&employee)

employee.ID = strconv.Itoa(id)

id += 1

employeeList = append(employeeList, employee)

json.NewEncoder(w).Encode(employee)

}
func ListEmployees(w http.ResponseWriter, r *http.Request) {

  json.NewEncoder(w).Encode(employeeList)

}
func GetEmployee(w http.ResponseWriter, r *http.Request) {

  params := mux.Vars(r)

  for _, item := range employeeList {

     if item.ID == params["id"] {

        json.NewEncoder(w).Encode(item)

        return

     }

  }

  json.NewEncoder(w).Encode(&Employee{})

}
func UpdateEmployee(w http.ResponseWriter, r *http.Request) {

  params := mux.Vars(r)

  var employee Employee

  for index, item := range employeeList {

     if item.ID == params["id"] {

        employeeList = append(employeeList[:index], employeeList[index+1:]...)

        break

     }

  }

  _ = json.NewDecoder(r.Body).Decode(&employee)

  employee.ID = params["id"]

  employeeList = append(employeeList, employee)

  json.NewEncoder(w).Encode(employee)

}
func DeleteEmployee(w http.ResponseWriter, r *http.Request) {

  params := mux.Vars(r)

  for index, item := range employeeList {

     if item.ID == params["id"] {

        employeeList = append(employeeList[:index], employeeList[index+1:]...)

        break

     }

     json.NewEncoder(w).Encode(Employee{})

  }

}

Testing

We have learned to write a simple API in Go and it is time for testing. For this, we can use postman.

1. Create

2. Get all employees

3. Get employee using id

4. Update

5. Delete

Cool..! So we have just learned to write a simple CRUD API in Go and here we didn’t use a database instead we have used mock data also we have used the gorilla/mux framework to implement the API.

Have a project in mind that includes complex tech stacks? We can be just what you’re looking for! Connect with us here.

Disclaimer: The opinions expressed in this article are those of the author(s) and do not necessarily reflect the positions of Dexlock.

  • Share Facebook
  • Share Twitter
  • Share Linkedin