简体   繁体   中英

How to dynamically parse request body in go fiber?

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.

eg:

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",
}

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.

func handler(c *fiber.Ctx) error {
    values, err := url.ParseQuery(strings(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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM