dsiv4041
dsiv4041
2018-12-05 04:07

使用POSTMAN访问FormValue Golang中的POST请求值

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doucou19961205 doucou19961205 3年前

    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")
    
    }
    
    点赞 评论 复制链接分享