I have no idea why I always receive an empty string when sending values in POSTMAN
func main(){
rtr := mux.NewRouter()
rtr.HandleFunc("/search", search).Methods("POST")
}
func search(w http.ResponseWriter, r *http.Request) {
name := r.FormValue("name") //returns empty
}
This is the body request in POSTMAN
screenshot for the body request
{
"name": "markus"
}
I tried to change the body request to form data
Screenshot for form data in post request
But it still didn't work.
Does anyone have a solution?
Thanks
What you have there is not a FormValue
but a JSON
body. If your JSON object is just a simple map of string to string, then you can do something like this:
func search(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body) // check for errors
keyVal := make(map[string]string)
json.Unmarshal(body, &keyVal) // check for errors
name := keyVal["name"]
// do whatever with name
}
Edit
If you need to parse a form value you need to call ParseForm()
func search(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
// handle err
}
name := r.FormValue("name")
}