我刚刚编写了我的第一个 Go 应用程序,它通过 http 下载和解组简单的 JSON 对象。Http内容被压缩: 'content-encoding': 'deflate'
我使用了几个众所周知的例子(像这样)。不幸的是,应用程序无法解析所需的 JSON,并出现非常罕见和奇怪的错误。我无法找出问题所在。任何帮助将不胜感激。
JSON 输入 (使用 Python 进行调试)
In [8]: r = requests.get("http://172.17.0.31:20000/top")
In [9]: r.text
Out[9]: u'{"timestamp":{"tv_sec":1428447555,"tv_usec":600186},"string_timestamp":"2015-04-07 22:59:15.600186","monitor_status":"enabled"}'
In [18]: r.headers
Out[18]: {'content-length': '111', 'content-type': 'application/json', 'connection': 'close', 'content-encoding': 'deflate'}
源代码(根据答案更新)
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Top struct {
Timestamp Timestamp `json:"timestamp"`
String_timestamp string `json:"string_timestamp"`
Monitor_status string `json:"monitor_status"`
}
type Timestamp struct {
Tv_sec int `json:"tv_sec"`
Tv_usec int `json:"tv_usec"`
}
func get_content() {
url := "http://172.17.0.31:20000/top"
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
fmt.Println(res)
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
fmt.Println(body)
var jsondata Top
err = json.Unmarshal(body, &jsondata)
if err != nil {
panic(err.Error())
}
fmt.Println(jsondata)
}
func main() {
get_content()
}
错误
[vitaly@thermaltake elliptics-manager]$ go run main.go
&{200 OK 200 HTTP/1.1 1 1 map[Content-Type:[application/json] Content-Length:[111] Content-Encoding:[deflate]] 0xc20803e340 111 [] true map[] 0xc208028820 <nil>}
panic: invalid character 'x' looking for beginning of value
UPD:谢谢大家。现在很明显,这个问题的原因是deflateHTTP 响应的压缩。但是,目前还不清楚如何在 Golang 中执行解压(请参阅此处)。
哔哔one
慕姐4208626
叮当猫咪
python中如何利用zlib压缩与解压字符串?
还是不太理解http数字开头的类型
解压缩
如何编写从ftp下载压缩文件的小工具
相关分类