2018-10-17 06:25:17 +00:00
|
|
|
package requests
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"compress/gzip"
|
|
|
|
"compress/zlib"
|
2019-07-17 18:20:09 +00:00
|
|
|
"io"
|
2018-10-17 06:25:17 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2019-07-17 18:20:09 +00:00
|
|
|
// Response 响应内容包含http.Response 已读
|
2018-10-17 06:25:17 +00:00
|
|
|
type Response struct {
|
2019-07-17 18:20:09 +00:00
|
|
|
readContent string
|
|
|
|
readResponse *http.Response
|
2018-10-17 06:25:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// FromHTTPResponse 生成Response 从标准http.Response
|
|
|
|
func FromHTTPResponse(resp *http.Response) (*Response, error) {
|
2019-07-17 18:20:09 +00:00
|
|
|
var err error
|
2018-10-17 06:25:17 +00:00
|
|
|
// 复制response 返回内容 并且测试是否有解压的需求
|
|
|
|
srcbuf, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
2018-12-22 16:15:24 +00:00
|
|
|
return nil, err
|
2018-10-17 06:25:17 +00:00
|
|
|
}
|
|
|
|
resp.Body.Close()
|
|
|
|
|
2018-12-17 17:36:18 +00:00
|
|
|
content := ""
|
2018-10-17 06:25:17 +00:00
|
|
|
srcReader := bytes.NewReader(srcbuf)
|
|
|
|
|
2019-07-17 18:20:09 +00:00
|
|
|
var reader io.ReadCloser
|
|
|
|
if reader, err = gzip.NewReader(srcReader); err == nil {
|
|
|
|
defer reader.Close()
|
|
|
|
buf, err := ioutil.ReadAll(reader)
|
2018-10-17 06:25:17 +00:00
|
|
|
if err != nil {
|
2018-12-22 16:15:24 +00:00
|
|
|
return nil, err
|
2018-10-17 06:25:17 +00:00
|
|
|
}
|
|
|
|
content = string(buf)
|
2019-07-17 18:20:09 +00:00
|
|
|
} else if reader, err = zlib.NewReader(srcReader); err == nil {
|
|
|
|
defer reader.Close()
|
|
|
|
buf, err := ioutil.ReadAll(reader)
|
2018-12-17 18:17:04 +00:00
|
|
|
if err != nil {
|
2018-12-22 16:15:24 +00:00
|
|
|
return nil, err
|
2018-10-17 06:25:17 +00:00
|
|
|
}
|
2018-12-17 18:17:04 +00:00
|
|
|
content = string(buf)
|
|
|
|
} else {
|
|
|
|
content = string(srcbuf)
|
2018-10-17 06:25:17 +00:00
|
|
|
}
|
|
|
|
|
2019-07-17 18:20:09 +00:00
|
|
|
return &Response{readContent: content, readResponse: resp}, nil
|
2018-10-17 06:25:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Content 返回解压后的内容
|
|
|
|
func (gresp *Response) Content() string {
|
2019-07-17 18:20:09 +00:00
|
|
|
return gresp.readContent
|
2018-10-17 06:25:17 +00:00
|
|
|
}
|