Gin框架渲染
2021-08-13 本文已影响0人
TZX_0710
JSON数据解析和绑定 ShouldBindJSON
客户端传参,后端解析绑定
package main import ( "github.com/gin-gonic/gin" "net/http" ) type Login struct { UserName string `form:"username" json:"username" uri:"username" xml:"username" binding:"required"` Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"` } func main() { //创建路由 r := gin.Default() //创建POST请求 r.POST("/login", func(context *gin.Context) { var login Login //把body映射到结构体里面取 if err := context.ShouldBindJSON(&login); err != nil { context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if login.UserName != "root" || login.Password != "admin" { context.JSON(http.StatusBadRequest, gin.H{"status": "304"}) return } //返回json格式 context.JSON(http.StatusOK, gin.H{"status": 200}) }) r.Run(":8088") }
postman进行测试
//request { "username":"root", "password":"admin" } //result { "status": 200 }
表单数据解析和绑定 Bind()
package main import ( "github.com/gin-gonic/gin" "net/http" ) type Login struct { UserName string `form:"username" json:"username" uri:"username" xml:"username" binding:"required"` Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"` } func main() { //创建路由 r := gin.Default() //创建POST请求 r.POST("/login", func(context *gin.Context) { var form Login //Bind默认解析并绑定form格式 if err := context.Bind(&login); err != nil { context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if form.UserName != "root" || form.Password != "admin" { context.JSON(http.StatusBadRequest, gin.H{"status": "304"}) return } //返回json格式 context.JSON(http.StatusOK, gin.H{"status": 200}) }) r.Run(":8088") }
URL数据解析和绑定
package main import ( "github.com/gin-gonic/gin" "net/http" ) type Login struct { UserName string `form:"username" json:"username" uri:"username" xml:"username" binding:"required"` Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"` } func main() { //创建路由 r := gin.Default() //创建POST请求 r.POST("/login", func(context *gin.Context) { var form Login //ShouldBindUri绑定URL格式 if err := context.ShouldBindUri(&login); err != nil { context.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if form.UserName != "root" || form.Password != "admin" { context.JSON(http.StatusBadRequest, gin.H{"status": "304"}) return } //返回json格式 context.JSON(http.StatusOK, gin.H{"status": 200}) }) r.Run(":8088") }
响应格式
c.JSON()//json格式响应 c.XML()//XML格式响应 c.YAML()//YAML格式响应 c.ProtoBuf()//ProtoBuf 谷歌开发的高效存储读取工具
同步异步
goroutine 机制可以方便的实现异步处理。