Go语言中如何将ioutil.ReadAll读取的内容转换为JSON格式返回
Go 接口实现请求内容JSON返回方案
完整可运行代码
package main import ( "encoding/json" "io/ioutil" "log" "net/http" ) // 定义返回的JSON结构,可根据业务需求调整字段 type Response struct { Content string `json:"content"` } func receive(w http.ResponseWriter, r *http.Request) { // 读取请求体,新增错误处理避免异常崩溃 reqBody, err := ioutil.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(map[string]string{"error": "读取请求体失败"}) return } // 必须设置JSON类型响应头,保证客户端正确识别格式 w.Header().Set("Content-Type", "application/json") // 封装为结构体后序列化为标准JSON对象返回 resp := Response{ Content: string(reqBody), } json.NewEncoder(w).Encode(resp) // 控制台打印请求内容保留原有逻辑 println(string(reqBody)) } func handleR() { http.HandleFunc("/", receive) log.Fatal(http.ListenAndServe(":30000", nil)) } func main() { handleR() }
实现说明
- 修复了原有代码中
receive函数缺少闭合大括号的语法错误 - 新增请求体读取的错误处理逻辑,覆盖异常场景
- 主动设置
Content-Type: application/json响应头,符合HTTP规范 - 通过带JSON标签的结构体封装返回内容,输出标准JSON对象格式;如果不需要外层封装、直接返回JSON字符串,可直接保留原有
json.NewEncoder(w).Encode(string(reqBody))写法
如果你要原封不动返回请求体本身的JSON内容(请求体本身为合法JSON),可以简化处理:
w.Header().Set("Content-Type", "application/json") w.Write(reqBody)
内容的提问来源于stack exchange,提问作者Fabian
相关产品推荐
相关产品推荐

