go 解析 http gzip body 数据
目录
问题
典型场景
┌──────────────┐ ┌───────────────┐
│ 第三方API │──Gzip─▶│ 你的Go服务 │
└──────────────┘ └───────────────┘
▲
└─ 需要解析压缩数据节省带宽
go 服务向第三方 API 发起请求获取数据,但是绝大多数第三方 API 的接口都会设置 gzip 压缩,优化接口性能,
那么 go 服务在获取 body 后就是一个 gzip 格式的数据,就需要先进行解压后才能展示使用
一、方案一:自动解压(推荐)
全局配置 http.Client, 实现自动解压
client := &http.Client{
Transport: &http.Transport{
// 自动处理Accept-Encoding
DisableCompression: false,
},
}
resp, _ := client.Get("https://api.example.com/data")
defer resp.Body.Close()
// 自动解压Gzip/Zlib数据
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
关于 http.Client 的其他参数说明,请移步文章:go 自定义 http client
二、方案二:手动解压
获取响应 body 后,使用 gzip 标准库进行解压
import "compress/gzip"
resp, _ := http.Get("https://api.example.com/compressed-data")
defer resp.Body.Close()
var reader io.Reader = resp.Body
if resp.Header.Get("Content-Encoding") == "gzip" {
gzReader, err := gzip.NewReader(resp.Body)
if err != nil {
panic(err)
}
defer gzReader.Close()
reader = gzReader
}
data, _ := io.ReadAll(reader)
常见问题
1. 解压后出现�特殊字符,乱码
-
检查 Content-Encoding 响应头,根据编码不同进行转换编码:Golang字符串编码转换
-
验证压缩算法一致性:
if _, err := gzip.NewReader(resp.Body); err != nil { // 非Gzip数据 }