首页 > 解决方案 > 在golang中将ioutil.ReadAll转换为json很热

问题描述

我正在尝试将响应转换为 golang 中的 json。

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

我的目标是有一个端点以 json 格式显示此响应。

标签: httpgomuxioutilsencoding-json-go

解决方案


您可以直接复制请求以响应。并且不要忘记关闭请求正文。

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

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

}

推荐阅读