REST API using “Gin-Gonic” Go-Lang
INTRODUCTION
If we want to have a look at how to build traditional web applications and micro-services in Go language, then there is a framework commonly used named as Gin framework. It is a framework that reduces boilerplate code that would normally go into building these applications. One of library we have in GO language for creating an HTTP server is net/http
using which we can easily create a HTTP server. but the point to consider here is that it is not so flexible and it requires some boilerplate code to implement. Therefore Gin comes into the play. It has those commonly used functionalities, e.g. routing, middleware support, rendering, that reduce boilerplate code and make writing web applications simpler. It is a high-performance micro-framework that can be used to build web applications and micro-services. Moreover we can say that it’s a GO equivalent of Flask that is used in Python.
After reading the documentation and some other stuff, we can have a look at the control flow for a web application, API server or a micro-service developed using Gin:
Request -> Route Parser -> [Middleware] -> Route Handler -> [Middleware] -> Response
- Request — that comes from the user side,
- Route Parser — It checks if the route definition is there or not, If yes then Gin invokes the route handler.
- Middleware — Part of code that can be executed during the handling of any HTTP request.
PRE-REQUISITES
For implementing and following this REST API tutorial, one must have Go and Git installed on his local machine. Moreover to install the Gin library one must follow the instruction;
go get -u github.com/gin-gonic/gin
LOOKING AT THE IMPLEMENTATION
First of all, importing the required libraries and packages is important, so here we are importing them;
package mainimport (
“net/http”
“github.com/gin-gonic/gin”
)
After importing the packages, we start with creating a struct named as User which we will later used in our POST request
type User struct {
Username string `json: username`
Password string `json: password`
}
Moving forward, we will create a function which will contain all our desired routes for GET and POST request, we will put all our routes in the function named as setupRouter, which we will call later in our main function;
func setupRouter() *gin.Engine { r := gin.Default()
// Ping test
r.GET(“/ping”, func(c *gin.Context) {
c.String(http.StatusOK, “pong”)
}) r.GET(“/”, func(c *gin.Context) {
c.String(http.StatusOK, “REST API”)
}) // Get user value
r.GET(“/user/:name”, func(c *gin.Context) {
user := c.Params.ByName(“name”)
c.JSON(http.StatusOK, gin.H{“user”: user})
}) // Get some JSON value
r.GET(“/getJSON”, func(c *gin.Context) {
data := map[string]interface{}{
“user”: “saad”,
“language”: “golang”,
}
c.AsciiJSON(http.StatusOK, data)
}) //using POST method, post some JSON and get back
r.POST(“/postdata”, func(c *gin.Context) {
var u User
c.BindJSON(&u)
c.JSON(http.StatusOK, gin.H{
“user”: u.Username,
“pass”: u.Password,
})
})
return r
}
We have put the whole function in the code block above, but for better understanding we will take chunks from the function above and have a look at them;
For creating the router
we are simply calling the function in Gin is as follows:
r := gin.Default()
This will simply creates a variable r that can be later used for the build of the application.
How we are defining the route handler
r.GET(“/ping”, func(c *gin.Context) {
c.String(http.StatusOK, “pong”)
})
We can easily define couple of routes in our application, Here we have created a route for ping-pong. The r.GET
method is used to define a route handler for a GET request. It has a pointer gin.Context
as a parameter. it usually includes information about the headers and cookies, etc.
Defining the main function
To start the application on localhost
and for serving on the 8080
port. The complete main.go
file looks as follows:
func main() {
r := setupRouter()
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
}
Executing the Application
For executing the application, run the following command;
go run helloworld.go
It will show the following output as shown in the figure below;
Checking the Results
For looking at the UI interface of the application, we can easily have a look at it in our browser;
http://localhost:8080/
We can test all the routes defined in our application easily;
GET REQUEST:http://localhost:8080/
http://localhost:8080/ping
http://localhost:8080/user/saad
http://localhost:8080/getJSON
For checking the POST request, we can use POSTMAN or we can also do it via curl request using command line;
POST REQUEST:curl --location --request POST 'localhost:8080/postdata' \
--header 'Content-Type: application/json' \
--data-raw '{
"Username":"saad",
"Password":"123"
}'
IN A NUTSHELL
For having a look at the complete code, you can access the code in the repository here;
Moving forward in part-II of this tutorial, we will have a look at introducing templates in our application structure, once we will introduce HTML pages and serving static content we must also follow some good standards for a clean architecture of any GO language application because clean code with good practices is a compulsory thing to follow.
For part-III, we can Dockerize the whole application and thus serving the REST-API from inside the container. Yes Docker (We contain everything).
HAPPY CODING !!!