【问题标题】:hot to convert ioutil.ReadAll into json in golang [duplicate]在golang中将ioutil.ReadAll转换为json很热[重复]
【发布时间】:2021-07-28 21:21:21
【问题描述】:

我正在尝试将响应转换为 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 格式显示此响应。

【问题讨论】:

    标签: http go mux ioutils encoding-json-go


    【解决方案1】:

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

    func receive(w http.ResponseWriter, r *http.Request) {
        defer r.Body.Close()
    
        _, err := io.Copy(w, r.Body)
        if err != nil {
            panic(err)
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 2015-07-10
      • 2016-12-02
      • 1970-01-01
      • 2019-05-03
      • 2019-10-24
      • 1970-01-01
      相关资源
      最近更新 更多