REST Api in Go using Gorilla/Mux

This post explains how to develop REST APIs in Go language using Gorilla Mux

Gorilla Mux is a package from the Gorilla Web Toolkit. It provides simple ways to create HTTP routers. Using the package, we can redirect program flow to respective HTTP handler functions.

Create a directory for the project

mkdir api-demo

Initialize a go project named ‘api-demo’

go mod init rinoymjoseph.github.com/api-demo

Install Gorilla Mux

go get -u github.com/gorilla/mux

Add a file named warrior.go which contains a type

package main

type Warrior struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

Add a file named handlers.go which contains handler functions

package main

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

func health(w http.ResponseWriter, r *http.Request) {
	log.Println("Entering health check")
	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, "API is up and running")
}

func getWarriors(w http.ResponseWriter, r *http.Request) {
	log.Println("Entering getWarriors")
	persons := buildWarriors()
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	jsonResponse, err := json.Marshal(persons)
	if err != nil {
		return
	}
	w.Write(jsonResponse)
}

func buildWarriors() []Warrior {
	var warriors []Warrior

	var warrior Warrior
	warrior.Id = 1
	warrior.Name = "Link"
	warriors = append(warriors, warrior)

	warrior.Id = 2
	warrior.Name = "Zelda"
	warriors = append(warriors, warrior)

	warrior.Id = 3
	warrior.Name = "Revali"
	warriors = append(warriors, warrior)
	return warriors
}

Create a main.go file and add below contents

package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

func main() {
	log.Println("Starting API server")
	//create a new router
	router := mux.NewRouter()
	log.Println("Creating routes")
	//specify endpoints
	router.HandleFunc("/health", health).Methods("GET")
	router.HandleFunc("/warriors", getWarriors).Methods("GET")
	http.Handle("/", router)
	//start and listen to requests
	http.ListenAndServe(":8080", router)
}

Get the packages

go get .
go mod tidy