Create REST API using gin in Golang

How to create simple REST API using golang and gin package


Golang is a programming language developed by Google. It can used to create cloud services, web , CLI tools etc. The first step to use Go is download and install the SDK.

Basic setup

To build basic API in Golang we need two packages.

go get github.com/gin-gonic/gin

Gin help us to build API routes . Local JSON data is used for the demonstration. In the main.go file add the following

package main

import  
("github.com/gin-gonic/gin"
"net/http")
 
// album represents data about a record album.
type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}

// albums slice to seed record album data.
var albums = []album{
    {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
    {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
    {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

func index(c *gin.Context){
	c.JSON(200,gin.H{"message": "hi there!"})
}

func getAlbums(c *gin.Context) {
    c.IndentedJSON(http.StatusOK, albums)
}

// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
    var newAlbum album

    // Call BindJSON to bind the received JSON to
    // newAlbum.
    if err := c.BindJSON(&newAlbum); err != nil {
        return
    }

    // Add the new album to the slice.
    albums = append(albums, newAlbum)
    c.IndentedJSON(http.StatusCreated, newAlbum)
}

// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {
    id := c.Param("id")

    // Loop through the list of albums, looking for
    // an album whose ID value matches the parameter.
    for _, a := range albums {
        if a.ID == id {
            c.IndentedJSON(http.StatusOK, a)
            return
        }
    }
    c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}

func main(){
	r:=gin.Default()
	r.GET("/",index)
	r.GET("/albums",getAlbums)
	r.POST("/albums", postAlbums)
	r.GET("/albums/:id", getAlbumByID)
	r.Run()
}

Here we created a gin instance which can be used to create API route. We also defined handler functions which handle the request.

:= is the short hand in Golang for creating variables

Run the project

By using go run . or go run main.go can execute the program.

Author: Manoj

Developer and a self-learner, love to work with Reactjs, Angular, Node, Python and C#.Net

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.