Jond
Jond

Reputation: 65

Access POST Request Value in FormValue Golang using POSTMAN

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

Upvotes: 0

Views: 5939

Answers (2)

Muhammad Tariq
Muhammad Tariq

Reputation: 4734

Just want to share additional information here.

Please check the Content-Type in Header section of Postman if you are facing any problem in sending your request to the server.

  • Set Content-Type to application/json for sending raw JSON in request.
  • Set Content-Type to application/x-www-form-urlencoded if you are sending form values in request. Also select x-www-form-urlencoded in postman's Body section

Upvotes: 0

ssemilla
ssemilla

Reputation: 3970

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")

}

Upvotes: 5

Related Questions