英文:
How do I get the body that was sent? Using gin gonic
问题
我如何获取发送的请求体?
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
fmt.Println("Hello, world!")
r := gin.Default()
r.POST("/", func(c *gin.Context) {
body := c.Request.Body
c.JSON(200, body)
})
r.Run(":8080")
}
我通过Postman发送了一个请求:
{
"email": "test@gmail.com",
"password": "test"
}
但是我得到的响应是一个空的JSON对象{}
,该怎么办?
英文:
How do I get the body that was sent?
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
fmt.Println("Hello, world!")
r := gin.Default()
r.POST("/", func(c *gin.Context) {
body := c.Request.Body
c.JSON(200,body);
})
r.Run(":8080");
}
I make a request via postman
{
"email": "test@gmail.com",
"password": "test"
}
and in response I get empty json {}
what to do?
答案1
得分: 3
你可以按照以下方式绑定传入的请求 JSON:
package main
import (
"github.com/gin-gonic/gin"
)
type LoginReq struct {
Email string
Password string
}
func main() {
r := gin.Default()
r.POST("/", func(c *gin.Context) {
var req LoginReq
c.BindJSON(&req)
c.JSON(200, req)
})
r.Run(":8080")
}
请记住,如果存在绑定错误,该方法会返回 400
。如果你想自己处理错误,可以尝试使用 ShouldBindJSON
方法,它会返回一个错误(如果有错误)或 nil
。
英文:
You can bind the incoming request json as follows:
package main
import (
"github.com/gin-gonic/gin"
)
type LoginReq struct {
Email string
Password string
}
func main() {
r := gin.Default()
r.POST("/", func(c *gin.Context) {
var req LoginReq
c.BindJSON(&req)
c.JSON(200, req)
})
r.Run(":8080")
}
Remember this method gives 400
if there is a binding error. If you want to handle error yourself, try ShouldBindJSON
which returns an error if any or nil
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论