68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package requests
|
|
|
|
import (
|
|
"bytes"
|
|
"compress/gzip"
|
|
"compress/zlib"
|
|
"io"
|
|
"io/ioutil"
|
|
"net/http"
|
|
)
|
|
|
|
// Response 响应内容包含http.Response 已读
|
|
type Response struct {
|
|
readContent string
|
|
readResponse *http.Response
|
|
}
|
|
|
|
// FromHTTPResponse 生成Response 从标准http.Response
|
|
func FromHTTPResponse(resp *http.Response, IsDecompressNoAccept bool) (*Response, error) {
|
|
var err error
|
|
// 复制response 返回内容 并且测试是否有解压的需求
|
|
srcbuf, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
resp.Body.Close()
|
|
|
|
content := ""
|
|
|
|
if IsDecompressNoAccept {
|
|
|
|
srcReader := bytes.NewReader(srcbuf)
|
|
var reader io.ReadCloser
|
|
if reader, err = gzip.NewReader(srcReader); err == nil {
|
|
defer reader.Close()
|
|
buf, err := ioutil.ReadAll(reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
content = string(buf)
|
|
} else if reader, err = zlib.NewReader(srcReader); err == nil {
|
|
defer reader.Close()
|
|
buf, err := ioutil.ReadAll(reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
content = string(buf)
|
|
} else {
|
|
content = string(srcbuf)
|
|
}
|
|
|
|
} else {
|
|
content = string(srcbuf)
|
|
}
|
|
|
|
return &Response{readContent: content, readResponse: resp}, nil
|
|
}
|
|
|
|
// Content 返回解压后的内容
|
|
func (gresp *Response) Content() string {
|
|
return gresp.readContent
|
|
}
|
|
|
|
// GetSrcResponse 获取原生golang http.Response
|
|
func (gresp *Response) GetSrcResponse() *http.Response {
|
|
return gresp.readResponse
|
|
}
|