How to dynamically parse request body in go fiber?

Issue

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

Solution

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
}

Answered By – mkopriva

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.