Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically parse request body in go fiber?

Tags:

go

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.

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",
}
like image 273
hamed dehghan Avatar asked Oct 11 '25 18:10

hamed dehghan


1 Answers

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
}
like image 56
Jan Švábík Avatar answered Oct 15 '25 18:10

Jan Švábík