删除请求的正文在我的golang rest api端点中为空

问题描述 投票:1回答:2

如果方法是DELETE,我似乎得到了golang http.Request的空主体内容。但是,如果我将方法更改为POST,则正文内容将提供我期望的内容。

我的golang中的相关代码如下:

import(
  "github.com/gorilla/handlers"
  "github.com/gorilla/mux"
)
func Delete(w http.ResponseWriter, r *http.Request) {
  r.ParseForm()
  qs := r.Form
  log.Println(qs)
}


func main() {
  router := mux.NewRouter()

  router.HandleFunc("/profile", Delete).Methods("POST")
  router.HandleFunc("/profile", Delete).Methods("DELETE")

}

现在,当我从浏览器运行此JavaScript代码时:

fetch(sendurl,{
  method:"POST",
  headers:{
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body:"data="+project.encodeFormURIComponent(JSON.stringify({"ids":[1032,1033]}))
})
.then(response=>{
  if(response.ok)
    return response.json();
})
.then(result=>{
  console.log(result);
})

我在Golang代码的qs[ids]中看到了一个不错的数字数组。但是,如果我在JavaScript中将method:"POST"更改为method:"DELETE",则qs为空。

我在做什么错?


UPDATE

此具有DELETE方法的JavaScript可以按通常期望的方式填充golang qs变量:

fetch(sendurl+"?data="+project.encodeFormURIComponent(JSON.stringify({"ids":[1032,1033]})),{
  method:"DELETE",
  headers:{
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
.then(response=>{
  if(response.ok)
    return response.json();
})
.then(result=>{
  console.log(result);
})

所以当使用body方法时,Golang似乎会忽略JavaScript DELETE参数,但是它将尊重API端点URL中的查询字符串内容吗?为什么会这样?

rest go http-delete
2个回答
0
投票

https://tools.ietf.org/html/rfc7231#section-4.3.5

DELETE请求消息中的有效载荷没有定义的语义;在DELETE请求上发送有效内容正文可能会导致某些现有的实现拒绝该请求。

查询字符串是请求target-uri的一部分;换句话说,查询字符串是identifier的一部分,而不是它的附带修饰符。但是请求的消息正文是标识符的[[not部分。

因此,不需要您的本地框架或转发您的请求的任何其他通用组件来为消息正文提供支持。

认为C中的“未定义行为”。

© www.soinside.com 2019 - 2024. All rights reserved.