learningtech
learningtech

Reputation: 33673

Body of delete request is empty in my rest api endpoint

I seem to get empty body content of a Go http.Request if the method is DELETE. But if I change the method to POST, then the body content gives me the content I expect.

The relevant code from my golang looks like this:

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

}

Now when I run this JavaScript code form my browser:

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);
})

I see a nice array of numbers in my qs[ids] in my Golang code. But if I change my method:"POST" to method:"DELETE" in the JavaScript, then qs is empty.

What am I doing wrong?


UPDATE

This JavaScript with the DELETE method can populate the Go qs variable the way one would normally expect:

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);
})

So it seems Go will ignore JavaScript body argument when DELETE method is used, but it will respect the query string content in the API endpoint url? Why is it like that?

Upvotes: 2

Views: 5070

Answers (1)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57204

https://www.rfc-editor.org/rfc/rfc7231#section-4.3.5

A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.

The query string is part of the target-uri of the request; in other words, the query string is part of the identifier, not an incidental modifier of it. But the message-body of the request is not part of the identifier.

So your local framework, or any of the other general purpose components forwarding your request, are not required to provide support for the message-body.

Think "undefined behavior" in C.

Upvotes: 3

Related Questions