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.

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.