This is a creation in Article, where the information may have evolved or changed.
0. Introduction
Gin is a fast HTTP framework for Golang, which is very handy and easy to use.
1. Get started quickly
package mainimport ("github.com/gin-gonic/gin")func main() { r := gin.Default() r.GET("/test", func(c *gin.Context) { //c.String(200,"1111") c.String(200,"test") }) r.Run() // listen and server on 0.0.0.0:8080}
The default port is 8080,http://localhost:8080/test, open the link as follows,
Test.png
You can see that building an HTTP request is very simple, if it is in spring, it is still configured, of course, Spring boot is configured very quickly, and then look back to JSON
2.json
package mainimport ("github.com/gin-gonic/gin")func main() { r := gin.Default() r.GET("/test", func(c *gin.Context) { //c.String(200,"1111") c.JSON(200, gin.H{ "code":0, "msg":"ok", "data":"data", }) }) r.Run() // listen and server on 0.0.0.0:8080}
The JSON you see on the page is: {"code": 0, "Data": "Data", "MSG": "OK"}
In the normal development, when we want to return JSON, often is a object to generate JSON, remember, especially deep in spring boot directly return an object to automatically help you generate JOSN, gin is how to do it, we look at,
package mainimport ("github.com/gin-gonic/gin")func main() { type Student struct { Name string Age int } r := gin.Default() r.GET("/test", func(c *gin.Context) { //c.String(200,"1111") c.JSON(200,Student{"la",17}) }) r.Run() // listen and server on 0.0.0.0:8080}
is not very simple, directly return to a struct.
3. Request with parameters
package mainimport ("github.com/gin-gonic/gin")func main() { r := gin.Default() r.GET("/test/:name", func(c *gin.Context) { name := c.Param("name") c.String(200, "Hello %s", name) }) r.Run()}
Take parameters through the Param () method, and the params () method can take multiple parameters.