The github.com/gin-gonic/gin package is another Go web framework that extends the capabilities of a Go HTTP server with many shorthand and auxiliary functions. Its features include the following:
- Speed: Its routing is fast and has very little memory footprint.
- Middleware: It allows to define and use intermediate handlers with a full control of their flow.
- Panic-free: It comes with middleware that recovers from panics.
- Grouping: It can group routes with the same prefix together.
- Errors: It manages and collects error that happen during the request.
- Rendering: It comes out of the box with renderers for most web formats (JSON, XML, HTML).
The core of the package is gin.Engine, which is also a http.Handler. The gin.Default function returns an engine that uses two middlewares—Logger, which prints the result of each HTTP request received, and Recovery, which recovers from panics. The other option is to use the gin.New function, which returns an engine with no middleware.
It allows us to bind a handler to a single HTTP method with a series of the engine's methods named after their HTTP counterpart:
- DELETE
- GET
- HEAD
- OPTIONS
- PATCH
- POST
- PUT
- Any (catch all for any HTTP method)
There's also a group method that returns a route grouping for the selected path, which exposes all of the preceding methods:
router := gin.Default()
router.GET("/resource", getResource)
router.POST("/resource", createResource)
router.PUT("/resource", updateResoure)
router.DELETE("/resource", deleteResource)
// with use grouping
g := router.Group("/resource")
g.GET("", getResource)
g.POST("", createResource)
g.PUT("", updateResoure)
g.DELETE("", deleteResource)
The handlers in this framework have a different signature. Instead of having a response writer and a request as arguments, it uses gin.Context, a structure that wraps both, and offers many shorthands and utilities. For instance, the package offers the possibility of using placeholders in the URL and the context enables these parameters to be read:
router := gin.Default()
router.GET("/hello/:name", func(c *gin.Context) {
c.String(http.StatusOK, "Hello %s!", c.Param("name"))
})
We can also see in the example that the context offers a String method that enables us to write an HTTP status and the content of the response with a one-liner.