-
Notifications
You must be signed in to change notification settings - Fork 8
/
response.go
90 lines (80 loc) · 1.59 KB
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package ghttp
import (
"compress/gzip"
"compress/zlib"
"encoding/json"
"io"
"io/ioutil"
"net/http"
)
// Response ghttp response
type Response struct {
*http.Response
Url string
Body *Body
req *http.Request
}
// Body
type Body struct {
reader io.ReadCloser
compressedReader io.ReadCloser
}
// Read
func (b *Body) Read(p []byte) (int, error) {
if b.compressedReader != nil {
return b.compressedReader.Read(p)
}
return b.reader.Read(p)
}
// Close
func (b *Body) Close() error {
err := b.reader.Close()
if b.compressedReader != nil {
return b.compressedReader.Close()
}
return err
}
// FromToJson
func (b *Body) FromToJson(o interface{}) error {
return json.NewDecoder(b).Decode(o)
}
// FromToString
func (b *Body) FromToString() (string, error) {
body, err := ioutil.ReadAll(b)
if err != nil {
return "", err
}
return string(body), nil
}
// Gzip
func Gzip() *compression {
reader := func(buffer io.Reader) (io.ReadCloser, error) {
return gzip.NewReader(buffer)
}
writer := func(buffer io.Writer) (io.WriteCloser, error) {
return gzip.NewWriter(buffer), nil
}
return &compression{
writer: writer,
reader: reader,
ContentEncoding: "gzip",
}
}
// Deflate
func Deflate() *compression {
reader := func(buffer io.Reader) (io.ReadCloser, error) {
return zlib.NewReader(buffer)
}
writer := func(buffer io.Writer) (io.WriteCloser, error) {
return zlib.NewWriter(buffer), nil
}
return &compression{
writer: writer,
reader: reader,
ContentEncoding: "deflate",
}
}
// Zlib
func Zlib() *compression {
return Deflate()
}