What is Gin in Golang?

Gin is a high-performance HTTP web framework written in Golang (Go). Gin has a martinia legacy web framework in Go-like API and claims to be up to 40 times faster.

Gin allows you to build web applications and microservices in Go. It contains a set of commonly used functionalities (e.g., routing, middleware support, rendering, etc.) that reduce boilerplate code and make it simpler to build web applications.

svg viewer

Installation

  1. Download and install:
go get -u github.com/gin-gonic/gin
  1. Import it into your code:
import "github.com/gin-gonic/gin"

Example

Let’s create a simple web server using Gin. gin.Default() creates a Gin router with default middleware: logger and recoverycrash-free middleware.
Next, we make a handler using router.GET(path, handle), where path is the relative path,​ and handle is the handler function that takes *gin.Context as an argument. The handler function serves a JSON response with a status of 200200.
Finally, we start the router using router.Run() that, by default, listens on port 80808080.

package main
import "github.com/gin-gonic/gin"
func main() {
// Creates a gin router with default middleware
router := gin.Default()
// A handler for GET request on /example
router.GET("/example", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "example",
}) // gin.H is a shortcut for map[string]interface{}
})
router.Run() // listen and serve on port 8080
}

Gin is an open-source project, you can read more about the API on the Github page.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved