How to dynamically parse request body in go fiber?

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

How to dynamically parse request body in go fiber?

问题

我有一个使用Go Fiber构建的API。
我正在尝试以动态方式解析请求体数据作为键值对。

我们知道,Fiber有context.Body()context.Bodyparser()方法可以做到这一点,但我找不到任何使用这些方法动态实现的正确示例。

例如:

func handler(c *fiber.Ctx) error {
	req := c.Body()
	fmt.Println(string(req))
	
    return nil
}

输出:

key=value&key2=value2&key3&value3

我想要的是一个动态的JSON,类似于:

{
    key:"value",
    key2:"value2",
    key3:"value3",
}
英文:

I have an API built in go fiber.
I'm tryng to parse request body data as key value pairs dynamically.

As we know, fiber has context.Body() and context.Bodyparser() methods to do this but I couldn't find any proper example to do this dynamically with these methods.

e.g:

func handler(c *fiber.Ctx) error {
	req := c.Body()
	fmt.Println(string(req))
	
    return nil
}

output:

key=value&key2=value2&key3&value3

What I'm looking for is a dynamic json like:

{
    key:"value",
    key2:"value2",
    key3:"value3",
}

答案1

得分: 6

内容的mime-typeapplication/x-www-form-urlencoded而不是application/json。要解析它,您可以使用net/url.ParseQuery。其结果是一个map[string][]string,您可以轻松地将其转换为map[string]string,然后使用encoding/json包将其编组为所需的JSON输出。

以下是您可以开始使用的代码:

func handler(c *fiber.Ctx) error {
    values, err := url.ParseQuery(string(c.Body()))
    if err != nil {
        return err
    }

    obj := map[string]string{}
    for k, v := range values {
        if len(v) > 0 {
            obj[k] = v[0]
        }
    }

    out, err := json.Marshal(obj)
    if err != nil {
        return err
    }
    
    fmt.Println(string(out))
    return nil
}
英文:

The content's mime-type is application/x-www-form-urlencoded not application/json. To parse that you can use net/url.ParseQuery. The result of that is a map[string][]string which you can then easily convert to a map[string]string and then marshal that with the encoding/json package to get your desired JSON output.

Here's a code you can start with:

func handler(c *fiber.Ctx) error {
    values, err := url.ParseQuery(string(c.Body()))
    if err != nil {
        return err
    }

    obj := map[string]string{}
    for k, v := range values {
        if len(v) > 0 {
            obj[k] = v[0]
        }
    }

    out, err := json.Marshal(obj)
    if err != nil {
        return err
    }
    
    fmt.Println(string(out))
    return nil
}

huangapple
  • 本文由 发表于 2022年3月8日 22:51:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/71396974.html
匿名

发表评论

匿名网友

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

确定