Sending body on HTTP GET request

I’ve heard a few times “you can’t, it’s not possible to send a body on a request made with GET method”. Well… You can. You can send a body on a GET request and you can read the body. It’s against the standards and you should not do it, as it will mess your design. But technically, it can be done.

package main

import (
   "encoding/json"
   "io/ioutil"
   "log"
   "net/http"
)

func main() {
   http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
      body, err := ioutil.ReadAll(r.Body)
      if err != nil {
         log.Println(err)
         return
      }

      input := &struct {
         A string `json:"a"`
         B string `json:"b"`
      }{}
      if err := json.Unmarshal(body, input); err != nil {
         log.Println(err)
         return
      }

      data, err := json.Marshal(input)
      if err != nil {
         log.Println(err)
         return
      }
      w.Write(data)
   })

   log.Fatal(http.ListenAndServe(":8118", nil))
}
curl -X GET \
  http://localhost:8118 \
  -H 'content-type: application/json' \
  -d '{"a": "val1", "b":"val2"}'
{"a":"val1","b":"val2"}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.