你可以使用gin gonic来获取发送的请求体。

huangapple go评论86阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年8月13日 02:39:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/68762668.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定