-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
60 lines (47 loc) · 1.34 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
package klient
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
var ResponseErrLimit int64 = 1 << 20 // 1MB
// ResponseFuncJSON returns a response function that decodes the response into data
// with json decoder. It will return an error if the response status code is not 2xx.
//
// If data is nil, it will not decode the response body.
func ResponseFuncJSON(data interface{}) func(*http.Response) error {
return func(resp *http.Response) error {
if err := UnexpectedResponse(resp); err != nil {
return err
}
// 204s, for example
if resp.ContentLength == 0 {
return nil
}
if data == nil {
return nil
}
if err := json.NewDecoder(resp.Body).Decode(data); err != nil {
return fmt.Errorf("decode response body: %w", err)
}
return nil
}
}
// LimitedResponse not close body, retry library draining it.
func LimitedResponse(resp *http.Response) []byte {
if resp == nil {
return nil
}
v, _ := io.ReadAll(io.LimitReader(resp.Body, ResponseErrLimit))
bodyRemains, _ := io.ReadAll(resp.Body)
totalBody := append(v, bodyRemains...)
resp.Body = io.NopCloser(bytes.NewReader(totalBody))
return v
}
// DrainBody reads the entire content of r and then closes the underlying io.ReadCloser.
func DrainBody(body io.ReadCloser) {
defer body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(body, ResponseErrLimit))
}