Building a REST API in Go using Gorilla Mux

Table of Contents

  1. Overview
  2. Prerequisites
  3. Setup
  4. Creating the REST API
  5. Testing the API
  6. Conclusion

Overview

In this tutorial, you will learn how to build a REST API in Go using the Gorilla Mux package. Gorilla Mux is a powerful URL router and dispatcher that enables creating flexible and modular APIs. By the end of this tutorial, you will have a working API with CRUD operations for a resource.

Prerequisites

To follow along with this tutorial, you should have basic knowledge of Go programming language syntax. It is also recommended to have Go installed on your system.

Setup

Before we start building the REST API, we need to set up our Go environment and install the necessary packages. Follow the steps below:

  1. Install Go from the official website: https://golang.org/dl/

  2. Verify that Go is installed properly by running the following command in your terminal: bash go version You should see the installed Go version.

  3. Create a new directory for your project and navigate to it: bash mkdir my-api && cd my-api

  4. Initialize a new Go module: bash go mod init github.com/your-username/my-api

  5. Install the Gorilla Mux package: bash go get -u github.com/gorilla/mux

Creating the REST API

Now, let’s start building our REST API with Gorilla Mux.

  1. Create a new file named main.go in your project directory.

  2. Add the following code to import the necessary packages and define the main function:

    ```go
    package main
       
    import (
    	"fmt"
    	"log"
    	"net/http"
       	
    	"github.com/gorilla/mux"
    )
       
    func main() {
    	router := mux.NewRouter()
    	log.Fatal(http.ListenAndServe(":8080", router))
    }
    ```
    Here, we import the required packages (`fmt`, `log`, `net/http`, and `github.com/gorilla/mux`) and create a new router using `mux.NewRouter()`. Our API will run on port 8080.
    
  3. Now, let’s define the routes for our API. Add the following code below the router initialization:

    ```go
    func main() {
    	router := mux.NewRouter()
       
    	// Routes
    	router.HandleFunc("/api/resource", getAllResources).Methods("GET")
    	router.HandleFunc("/api/resource/{id}", getResource).Methods("GET")
    	router.HandleFunc("/api/resource", createResource).Methods("POST")
    	router.HandleFunc("/api/resource/{id}", updateResource).Methods("PUT")
    	router.HandleFunc("/api/resource/{id}", deleteResource).Methods("DELETE")
       
    	log.Fatal(http.ListenAndServe(":8080", router))
    }
    ```
    Here, we define five routes for our API: `GET` all resources, `GET` a specific resource by ID, `POST` a new resource, `PUT` (update) a resource, and `DELETE` a resource. Each route corresponds to a specific function which we will define next.
    
  4. Let’s define the functions for each route. Add the following code below the main function:

    ```go
    func getAllResources(w http.ResponseWriter, r *http.Request) {
    	// Logic to get all resources
    }
       
    func getResource(w http.ResponseWriter, r *http.Request) {
    	// Logic to get a single resource
    }
       
    func createResource(w http.ResponseWriter, r *http.Request) {
    	// Logic to create a new resource
    }
       
    func updateResource(w http.ResponseWriter, r *http.Request) {
    	// Logic to update a resource
    }
       
    func deleteResource(w http.ResponseWriter, r *http.Request) {
    	// Logic to delete a resource
    }
    ```
    Here, we have defined placeholder functions for each route. You will implement the actual logic inside these functions according to your API requirements.
    
  5. Finally, let’s run our API. Open your terminal and navigate to your project directory. Run the following command: bash go run main.go You should see an output indicating that your API is running on http://localhost:8080.

Testing the API

To test the API routes, you can use tools like curl or Postman. Here are some examples:

  1. Get all resources: bash curl http://localhost:8080/api/resource

  2. Get a specific resource: bash curl http://localhost:8080/api/resource/123

  3. Create a new resource: bash curl -X POST -H "Content-Type: application/json" -d '{"name":"New Resource"}' http://localhost:8080/api/resource

  4. Update a resource: bash curl -X PUT -H "Content-Type: application/json" -d '{"name":"Updated Resource"}' http://localhost:8080/api/resource/123

  5. Delete a resource: bash curl -X DELETE http://localhost:8080/api/resource/123

Conclusion

In this tutorial, you have learned how to build a REST API in Go using Gorilla Mux. You learned how to set up your development environment, install necessary packages, define routes, and implement the logic for each route. You also tested the API using curl commands. Now, you can further expand the functionality of your API based on your requirements, and explore more features of Gorilla Mux to enhance your Go web development experience.