How do I convert post request body to query string format on go fasthttp/gofiber?

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

How do I convert post request body to query string format on go fasthttp/gofiber?

问题

这是我使用Get请求的代码:

app.Get("/", func(c *fiber.Ctx) error {
    fmt.Println(string(c.Request().URI().QueryString()))
    return c.SendString("Ok!")
})

我得到了以下输出:

hello=12&sdsdf=324

我想在POST请求中做同样的事情。我尝试了string(c.Body()),但我得到了以下输出:

----------------------------948304762891896410291124
Content-Disposition: form-data; name="hello"

ge
----------------------------948304762891896410291124
Content-Disposition: form-data; name="ge"

dsfs
----------------------------948304762891896410291124--

如何获得一个类似于查询字符串格式的POST输出。POST参数可以是任何内容和任意数量。

英文:

This is what I'm doing with Get requests

app.Get("/", func(c *fiber.Ctx) error {


    fmt.Println(string(c.Request().URI().QueryString()))
    
    return c.SendString("Ok!")
  })

I'm getting the following output

hello=12&sdsdf=324

I want to do the same for POST request. I tried string(c.Body()) but I got output like the following

----------------------------948304762891896410291124
Content-Disposition: form-data; name="hello"

ge
----------------------------948304762891896410291124
Content-Disposition: form-data; name="ge"

dsfs
----------------------------948304762891896410291124--

How can I get a query string format out put for POST. The post parameters can be anything and any number.

答案1

得分: 3

你可以尝试使用BodyParser方法,文档链接在https://docs.gofiber.io/api/ctx#bodyparser

type Person struct {
    Name string `json:"name" xml:"name" form:"name"`
}

app.Post("/", func(c *fiber.Ctx) error {
        p := new(Person)
        if err := c.BodyParser(p); err != nil {
            return err
        }
        log.Println(p.Name)
        return nil
})
英文:

You could try BodyParser method, the Document Link at https://docs.gofiber.io/api/ctx#bodyparser


type Person struct {
    Name string `json:"name" xml:"name" form:"name"`
}

app.Post("/", func(c *fiber.Ctx) error {
        p := new(Person)
        if err := c.BodyParser(p); err != nil {
            return err
        }
        log.Println(p.Name)
        return nil
})

huangapple
  • 本文由 发表于 2022年4月19日 21:39:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/71925959.html
匿名

发表评论

匿名网友

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

确定