I want to get all the post form data and get the values as string, however using PostParams I am able to get all the post data, but the values are as array key: [value], how can I get all the form data as string values?
[Edit] I may not stated clearly, but I need to get the whole form as JSON, because I need to send the form data to another API which need the body as JSON data
form.html
<form>
<input type='text' name='key' />
<input type='text' name='key2' />
</form>
script.js
$.ajax( {
url: '/post/action',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false
}).done(function(r) {
console.log(r);
});
action.go
func PostAction(c echo.Context) error {
form, _ := c.FormParams()
b, _ := json.Marshal(form)
log.Println(b) // this will print: key: [value], key2: [value]
// I want to get value as string: key: value, key2: value
// ..other function, return, etc
}
How can I get the form values as string? Or is there another function that does this?
Thank you very much in advance
No need to JSON marshal the already decoded form, simply do:
form["key"][0]
form["key2"][0]
See the docs on c.FormParams
and then click on the return type to see its documentation, and you'll notice that it's just the stdlib's url.Values
type, which is defined as a map of string slices (i.e., map[string][]string
).
If you need to convert a value of type url.Values
to a "simple object", you can convert it to a map[string]string
using the following code:
o := make(map[string]string, len(form))
for k, v := range form {
// if you are certain v[0] is present
o[k] = v[0]
// if you are not sure v[0] is present, check first
if len(v) > 0 {
o[k] = v[0]
}
}
data, err := json.Marshal(o)
if err != nil {
return err
}
// ...