
本文详解如何在 go 中发起 post 请求后读取、关闭响应体,并解析返回的 json 数据,避免仅输出响应头而丢失关键业务数据(如 magento 的购物车 id)。
本文详解如何在 go 中发起 post 请求后读取、关闭响应体,并解析返回的 json 数据,避免仅输出响应头而丢失关键业务数据(如 magento 的购物车 id)。
在 Go 中使用 http.Post 发起请求时,返回的是 *http.Response 类型对象,它仅封装了 HTTP 状态、头信息和响应体流(Body),并不会自动读取或解码响应内容。因此,直接打印 resp 会看到类似 {200 OK ... map[Content-Type:[application/json; ...]} 的结构体输出——这只是响应元信息,真正的 JSON 数据(例如 Magento 返回的购物车 ID 字符串)仍驻留在 resp.Body 中,需手动读取。
✅ 正确步骤:读取 + 关闭 + 解析
首先,必须调用 resp.Body.Close() 释放资源(Go 官方强烈建议),否则可能引发连接泄漏;其次,需从 Body 中读取字节流,并根据需要解析为字符串或结构体。
以下是完整、健壮的实现示例:
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
var protocol = "http://"
var baseURL = protocol + "myserver.dev"
func main() {
fmt.Print("Start API Test on: " + baseURL + "\n")
resp, err := getCart()
if err != nil {
fmt.Fprintf(os.Stderr, "Request failed: %v\n", err)
os.Exit(1)
}
defer resp.Body.Close() // 关键:务必延迟关闭响应体
// 方式 1:直接输出原始 JSON 响应(调试用)
fmt.Print("Raw JSON response:\n")
_, err = io.Copy(os.Stdout, resp.Body)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read body: %v\n", err)
os.Exit(1)
}
fmt.Println()
// 方式 2:解析为 Go 结构体(推荐用于生产)
// 假设 Magento 返回格式为 {"id": "a1b2c3..."}
var cart struct {
ID string `json:"id"`
}
resp2, err := getCart() // 重新发起请求(因 Body 已被上一步读取耗尽)
if err != nil {
fmt.Fprintf(os.Stderr, "Retry request failed: %v\n", err)
os.Exit(1)
}
defer resp2.Body.Close()
if err := json.NewDecoder(resp2.Body).Decode(&cart); err != nil {
fmt.Fprintf(os.Stderr, "JSON decode error: %v\n", err)
os.Exit(1)
}
fmt.Printf("Retrieved cart ID: %s\n", cart.ID)
}
func getCart() (*http.Response, error) {
// 注意:实际使用需添加必要 Header(如 Authorization、Content-Type)
req, err := http.NewRequest("POST", baseURL+"/index.php/rest/V1/guest-carts/", nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
return client.Do(req)
}⚠️ 关键注意事项
-
Body只能被读取一次:io.Copy或json.Decoder.Decode会消耗整个流,后续再读将得到空结果。如需多次使用,应先用ioutil.ReadAll(Go 1.16+ 推荐io.ReadAll)缓存字节切片。 -
始终
Close()响应体:即使发生错误,也应在if err != nil分支中检查resp != nil后关闭,防止连接池耗尽。 -
设置正确 Header:Magento REST API 通常要求
Content-Type: application/json,部分接口还需Authorization或Accept: application/json,缺失可能导致 400/401 错误。 -
错误处理不可省略:网络请求易失败,需逐层检查
err,而非仅依赖resp.StatusCode。
通过以上实践,你就能稳定获取与 curl 完全一致的 JSON 响应内容,并安全集成到 Go 应用逻辑中。


















