Sql FormValue始终是空映射
我为我的处理程序编程了多种方法,例如:Sql FormValue始终是空映射,sql,rest,go,Sql,Rest,Go,我为我的处理程序编程了多种方法,例如: func DeleteProduct(w http.ResponseWriter, r *http.Request){ log.Println(r.Form) db.Exec("Delete from products where Id = "+r.FormValue("Id")) } type ReqBody struct { CustomerDateTime string `json:"CustomerDateTime"`
func DeleteProduct(w http.ResponseWriter, r *http.Request){
log.Println(r.Form)
db.Exec("Delete from products where Id = "+r.FormValue("Id"))
}
type ReqBody struct {
CustomerDateTime string `json:"CustomerDateTime"`
CustomerDateTime string `json:"CustomerDateTime"`
UserId int `json:"UserId"`
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
// Error handler...
}
rb := ReqBody{}
json.Unmarshal(body, &rb)
// Now you can perform something like this:
println(rb.UserId)
问题是r.Form始终是一个空映射,在我的删除请求中,我以JSON格式发送Id,如下所示:
{
"CustomerDate": "13.03.2018",
"CustomerDateTime": "13:30",
"UserId": 4
}
router.HandleFunc("/delete",handler.DeleteProduct).Methods("DELETE")
在main方法中,我注册了如下处理程序方法:
{
"CustomerDate": "13.03.2018",
"CustomerDateTime": "13:30",
"UserId": 4
}
router.HandleFunc("/delete",handler.DeleteProduct).Methods("DELETE")
为什么r.Form和r.PostForm总是一个空映射?如果是JSON请求,在使用前必须
解组请求正文
任何参数
例如:
func DeleteProduct(w http.ResponseWriter, r *http.Request){
log.Println(r.Form)
db.Exec("Delete from products where Id = "+r.FormValue("Id"))
}
type ReqBody struct {
CustomerDateTime string `json:"CustomerDateTime"`
CustomerDateTime string `json:"CustomerDateTime"`
UserId int `json:"UserId"`
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
// Error handler...
}
rb := ReqBody{}
json.Unmarshal(body, &rb)
// Now you can perform something like this:
println(rb.UserId)
特别是这一部分“此字段仅在调用ParseForm后可用。”顺便说一句,如果尚未调用,则应调用ParseForm
。其次,更重要的是表单不包含json数据。解析后的表单将保存作为application/x-www-Form-urlencoded
+作为查询参数发送的数据,如果没有发送此类数据,则即使在解析后表单也将为空。请参阅此处,了解如何从与您的问题无关的请求中获取json,但这样会使您面临巨大的SQL注入攻击。请在SQL查询中使用占位符,而不是使用字符串连接构建查询。发布JSON文档不是HTML表单的工作方式。感谢您的快速回答,我明白你想告诉我什么,但我如何才能访问正文?@JohannesGnadlinger你可以使用req.body
其中req是req*http.Request
。是的,我已经认为这是解决方案,但我需要一个字节[]来反汇编,而不是一个io。ReadCloser@JohannesGnadlinger您还必须执行:body,err:=ioutil.ReadAll(req.Body)
太棒了,谢谢你的帮助,现在终于可以用了。我对这种语言不熟悉,你在这里真的帮了我:)