问题描述
我正在尝试将响应转换为 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()
}
解决方法
您可以直接复制请求进行响应。并且不要忘记关闭请求正文。
func receive(w http.ResponseWriter,r *http.Request) {
defer r.Body.Close()
_,err := io.Copy(w,r.Body)
if err != nil {
panic(err)
}
}