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.

How to create API using mux in Golang

How to create simple API using golang and mux 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/gorilla/mux

Mux help us to build API routes . In the main.go file add the following

package main

import  
("github.com/gorilla/mux"
"net/http"
"fmt")

// 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(w http.ResponseWriter, r *http.Request){
 fmt.Fprint(w,"Hello world!")
}

func getAlbums(w http.ResponseWriter, r *http.Request){
 fmt.Fprint(w,albums)
}
func main(){
	r:=mux.NewRouter()
	r.HandleFunc("/",index).Methods("GET")
	r.HandleFunc("/albums",getAlbums)
	fmt.Println("Server starting")
	http.ListenAndServe(":8080",r)

	 }

Here we create a mux router instance which can be used to create API route. We also define handler function for the API too.

:= 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.

How to create API using gin in Golang

How to create simple 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 . In the main.go file add the following

package main

import  
("github.com/gin-gonic/gin"
"net/http")

  func index(c *gin.Context){
	c.JSON(200,gin.H{"message": "Welcome to Golang API"})
}

func main(){
	r:=gin.Default()
    r.GET("/",index)
	r.Run()
}

Here we create a gin instance which can be used to create API route. We also define handler function for the API too.

:= 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.

How to create API using Fiber in Golang

How to create simple API using golang and express like Fiber 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 following packages

go get -u github.com/gofiber/fiber/v2

Fiber is express inspired library, if you were familiar with Nodejs express package, no worries . In the main.go file add the following

package main

import  
("github.com/gofiber/fiber/v2"
"fmt"
"log"
)
 
func api(c *fiber.Ctx) error {
    msg := fmt.Sprintf("✋ %s", c.Params("*"))
    return c.SendString(msg) // => ✋ register
}


func index(c *fiber.Ctx) error {
    return c.SendString("I am Fiber") // => ✋ register
}


func main(){
	app:= fiber.New()
    app.Get("/",index )
    app.Get("/api/*",api )
    log.Fatal(app.Listen(":3000"))
}

Here we create a Fiber router instance which can be used to create API route. We also define handler function for the API too.

:= 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.