Building REST API With Golang Using Mux

In this article we will let you know how to create REST apis using Mux

There are many libraries in Golang to create REST api. Out of these, Mux is very popular and stable library available to create REST api. In this article we will let you know how to create REST api’s using Mux



Project Setup and dependencies
As mentioned above, we are going to use mux library. So, go get the mux library using following command.
go get github.com/gorilla/mux

Create a file restapi.go and open it in any of your favorite text editor. Now, create basic rest api using following code.
package main

import (
"encoding/json"
"log"
"net/http"

"github.com/gorilla/mux"
)

func main() {
router := mux.NewRouter()
log.Fatal(http.ListenAndServe(":8080", router))
}

Once you run this code, server starts on port 8080 however you can’t navigate as route points are not available yet.

Create Model

In go we use struct to create model. In this example we are using Emp with following variables
type Emp struct {
Id string `json:"id,omitempty"`
FirstName string `json:"firstName,omitempty"`
LastName string `json:"lastName,omitempty"`
Age int `json:"age,omitempty"`
}

Add Endpoints

As discussed above, create endpoints
func GetEmps(w http.ResponseWriter, r *http.Request) {
}

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

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

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

func main() {
router := mux.NewRouter()

router.HandleFunc("/emp", GetEmps).Methods("GET")
router.HandleFunc("/emp/{id}", GetEmp).Methods("GET")
router.HandleFunc("/emp", CreateEmp).Methods("POST")
router.HandleFunc("/emp/{id}", DeleteEmp).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8080", router))
}

Data to support endpoints

In this example, we are using slice which contains following data to support endpoint.
var emps []Emp
emps = append(emps, Emp{"E-1", "Anupam", "Raj", 20})
emps = append(emps, Emp{"E-2", "Rahul", "Anand", 30})

Get All Emps

implement function GetEmps to return all employees as follow.
func GetEmps(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(emps)
}


Get Employee based on id

Above endpoint returns all the employees available with the emps slice. In this function we will return the employee based on the id(from request)
func GetEmp(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, emp := range emps {
if emp.Id == params["id"] {
json.NewEncoder(w).Encode(emp)
return
}
}
json.NewEncoder(w).Encode(&Emp{})
}

Other EndPoints

Create a employee and delete employee based on id as follow
func CreateEmp(w http.ResponseWriter, r *http.Request) {
var emp Emp
_ = json.NewDecoder(r.Body).Decode(&emp)
emps = append(emps, emp)
json.NewEncoder(w).Encode(emp)
}

func DeleteEmp(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, emp := range emps {
if emp.Id == params["id"] {
emps = append(emps[:index], emps[index+1:]...)
break
}
json.NewEncoder(w).Encode(emps)
}
}

Complete Code

Now put together everything, the code will be like
package main

import (
"encoding/json"
"log"
"net/http"

"github.com/gorilla/mux"
)

type Emp struct {
Id string `json:"id,omitempty"`
FirstName string `json:"firstName,omitempty"`
LastName string `json:"lastName,omitempty"`
Age int `json:"age,omitempty"`
}

var emps []Emp

func GetEmps(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(emps)
}

func GetEmp(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for _, emp := range emps {
if emp.Id == params["id"] {
json.NewEncoder(w).Encode(emp)
return
}
}
json.NewEncoder(w).Encode(&Emp{})
}

func CreateEmp(w http.ResponseWriter, r *http.Request) {
var emp Emp
_ = json.NewDecoder(r.Body).Decode(&emp)
emps = append(emps, emp)
json.NewEncoder(w).Encode(emp)
}

func DeleteEmp(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
for index, emp := range emps {
if emp.Id == params["id"] {
emps = append(emps[:index], emps[index+1:]...)
break
}
json.NewEncoder(w).Encode(emps)
}
}

func main() {
router := mux.NewRouter()
emps = append(emps, Emp{"E-1", "Anupam", "Raj", 20})
emps = append(emps, Emp{"E-2", "Rahul", "Anand", 30})

router.HandleFunc("/emp", GetEmps).Methods("GET")
router.HandleFunc("/emp/{id}", GetEmp).Methods("GET")
router.HandleFunc("/emp", CreateEmp).Methods("POST")
router.HandleFunc("/emp/{id}", DeleteEmp).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8080", router))
}

Run the app

use go run restapi.go command to start the application.

Never miss a post from Gufran Mirza, when you sign up for Ednsquare.