68 lines
1.3 KiB
Go
68 lines
1.3 KiB
Go
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()
|
|
|
|
// cbuf := bytes.NewBuffer([]byte{})
|
|
// _, err = io.Copy(cbuf, bytes.NewReader(srcbuf))
|
|
|
|
// if err != nil {
|
|
// panic(err)
|
|
// }
|
|
|
|
// resp.Body = ioutil.NopCloser(cbuf)
|
|
|
|
content := ""
|
|
srcReader := bytes.NewReader(srcbuf)
|
|
|
|
r, err := gzip.NewReader(srcReader)
|
|
defer r.Close()
|
|
if err == nil {
|
|
buf, err := ioutil.ReadAll(r)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
content = string(buf)
|
|
} else {
|
|
r, err := zlib.NewReader(srcReader)
|
|
defer r.Close()
|
|
if err == nil {
|
|
buf, err := ioutil.ReadAll(r)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
content = string(buf)
|
|
} else {
|
|
content = string(srcbuf)
|
|
}
|
|
}
|
|
|
|
return &Response{DContent: content, GResponse: resp}, nil
|
|
}
|
|
|
|
// Content 返回解压后的内容
|
|
func (gresp *Response) Content() string {
|
|
return gresp.DContent
|
|
}
|