REST API using “Gin-Gonic” Go-Lang


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.

Request -> Route Parser -> [Middleware] -> Route Handler -> [Middleware] -> Response
  • 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.


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


First of all, importing the required libraries and packages is important, so here we are importing them;

package mainimport (
type User struct {
Username string `json: username`
Password string `json: password`
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.JSON(http.StatusOK, gin.H{
“user”: u.Username,
“pass”: u.Password,

return r
r := gin.Default()
r.GET(“/ping”, func(c *gin.Context) {
c.String(http.StatusOK, “pong”)
func main() {
r := setupRouter()
// Listen and Server in
go run helloworld.go
Output of “go run helloworld.go” command
GET REQUEST:http://localhost:8080/
POST REQUEST:curl --location --request POST 'localhost:8080/postdata' \
--header 'Content-Type: application/json' \
--data-raw '{


For having a look at the complete code, you can access the code in the repository here;

Python, DevOps, Cryptography, Infra-Structure, Automation.