dsiv4041 2018-12-05 04:07
浏览 633
已采纳

使用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 2018-12-05 04:32
    关注

    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")
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 unity terrain打包后地形错位,跟建筑不在同一个位置,怎么办
  • ¥15 FileNotFoundError 解决方案
  • ¥15 uniapp实现如下图的图表功能
  • ¥15 u-subsection如何修改相邻两个节点样式
  • ¥30 vs2010开发 WFP(windows filtering platform)
  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式
  • ¥15 如果要做一个老年人平板有哪些需求
  • ¥15 k8s生产配置推荐配置及部署方案