http - 在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 格式显示此响应。
解决方案
您可以直接复制请求以响应。并且不要忘记关闭请求正文。
func receive(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
_, err := io.Copy(w, r.Body)
if err != nil {
panic(err)
}
}
推荐阅读
- r - 如何在 R 中生成多个不同长度的向量?
- css - 用于功能区/三角旗类型形状内的文本的 CSS
- python - BeautifulSoup 解析问题一些 div 没有显示
- c++ - 代码行数是否对 C++ 中的整个编译时间有影响?
- javascript - 有没有办法让 div 与任何网站重叠(便签应用程序)
- java - 如何在 Apache Camel 3.4.2 版中使用 EventNotifierSupport 记录事件?
- c - 如何用分号而不是点读取双精度值
- crystal-reports - 圆形功能在水晶报表中无法正常工作
- python - 导入中的停止循环
- pact-broker - 如何从 Pact-broker 备份现有的 Pact 合约?