-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.go
More file actions
53 lines (42 loc) · 1.15 KB
/
response.go
File metadata and controls
53 lines (42 loc) · 1.15 KB
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
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.
// - Return limited response body
// - Ready all body and assign it back to resp.Body
func LimitedResponse(resp *http.Response) []byte {
if resp == nil {
return nil
}
v, _ := io.ReadAll(io.LimitReader(resp.Body, ResponseErrLimit))
resp.Body = NewMultiReader(io.NopCloser(bytes.NewReader(v)), resp.Body)
return v
}