requests/response.go

75 lines
1.3 KiB
Go
Raw Normal View History

2018-10-17 06:25:17 +00:00
package requests
import (
"bytes"
"compress/gzip"
"compress/zlib"
"io/ioutil"
"net/http"
)
// Response 响应内容包含http.Response
type Response struct {
DContent string
GResponse *http.Response
}
// FromHTTPResponse 生成Response 从标准http.Response
func FromHTTPResponse(resp *http.Response) (*Response, error) {
// 复制response 返回内容 并且测试是否有解压的需求
srcbuf, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
resp.Body.Close()
2018-12-17 16:57:31 +00:00
// cbuf := bytes.NewBuffer([]byte{})
// _, err = io.Copy(cbuf, bytes.NewReader(srcbuf))
2018-10-17 06:25:17 +00:00
2018-12-17 16:57:31 +00:00
// if err != nil {
// panic(err)
// }
2018-10-17 06:25:17 +00:00
2018-12-17 16:57:31 +00:00
// resp.Body = ioutil.NopCloser(cbuf)
2018-10-17 06:25:17 +00:00
2018-12-17 17:36:18 +00:00
content := ""
2018-10-17 06:25:17 +00:00
srcReader := bytes.NewReader(srcbuf)
2018-12-17 17:36:18 +00:00
r, err := gzip.NewReader(srcReader)
if err == nil {
2018-12-17 17:42:38 +00:00
defer r.Close()
2018-10-17 06:25:17 +00:00
buf, err := ioutil.ReadAll(r)
if err != nil {
panic(err)
}
content = string(buf)
2018-12-17 17:36:18 +00:00
} else {
2018-12-17 17:42:38 +00:00
if r != nil {
r.Close()
}
2018-12-17 17:36:18 +00:00
r, err := zlib.NewReader(srcReader)
if err == nil {
2018-12-17 17:42:38 +00:00
defer r.Close()
2018-12-17 17:36:18 +00:00
buf, err := ioutil.ReadAll(r)
if err != nil {
panic(err)
}
content = string(buf)
} else {
2018-12-17 17:42:38 +00:00
if r != nil {
r.Close()
}
2018-12-17 17:36:18 +00:00
content = string(srcbuf)
2018-10-17 06:25:17 +00:00
}
}
return &Response{DContent: content, GResponse: resp}, nil
}
// Content 返回解压后的内容
func (gresp *Response) Content() string {
return gresp.DContent
}