hot to convert ioutil.ReadAll into json in golang

1k Views Asked by At

I'm trying to convert a response into json in golang.

func receive(w http.ResponseWriter, r *http.Request) {
  reqBody, _ := ioutil.ReadAll(r.Body)

  json.NewEncoder(w).Encode(string(reqBody))

  println(string(reqBody))


func handleR() {
  http.HandleFunc("/", receive)
  log.Fatal(http.ListenAndServe(":30000", nil))
}

func main() {
  handleR()
}

My goal is to have an endpoint to show this response in json.

1

There are 1 best solutions below

0
On

You can copy the request directly to respond. And don't forget about closing of the request body.

func receive(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()

    _, err := io.Copy(w, r.Body)
    if err != nil {
        panic(err)
    }

}