-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathresponse_handler.go
79 lines (65 loc) · 2.37 KB
/
response_handler.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
package requests
import (
"encoding/json"
"fmt"
"gopkg.in/yaml.v2"
"io"
"net/http"
"reflect"
)
type ResponseHandler[Response any] func(httpResponse *http.Response) (Response, error)
func BytesResponseHandler(readResponseOnStatusCodeIn ...int) ResponseHandler[[]byte] {
// By default, the response body is read only when the status code is 200
if len(readResponseOnStatusCodeIn) == 0 {
readResponseOnStatusCodeIn = append(readResponseOnStatusCodeIn, http.StatusOK, http.StatusNotFound)
}
return func(httpResponse *http.Response) ([]byte, error) {
for _, status := range readResponseOnStatusCodeIn {
if status == httpResponse.StatusCode {
responseBodyBytes, err := io.ReadAll(httpResponse.Body)
if err != nil {
return nil, fmt.Errorf("response statuc code: %d, read body error: %s", httpResponse.StatusCode, err.Error())
}
return responseBodyBytes, nil
}
}
return nil, fmt.Errorf("response status code: %d", httpResponse.StatusCode)
}
}
func StringResponseHandler(readResponseOnStatusCodeIn ...int) ResponseHandler[string] {
return func(httpResponse *http.Response) (string, error) {
responseBytes, err := BytesResponseHandler(readResponseOnStatusCodeIn...)(httpResponse)
if err != nil {
return "", err
}
return string(responseBytes), nil
}
}
func YamlResponseHandler[Response any](readResponseOnStatusCodeIn ...int) ResponseHandler[Response] {
return func(httpResponse *http.Response) (Response, error) {
var r Response
responseBytes, err := BytesResponseHandler(readResponseOnStatusCodeIn...)(httpResponse)
if err != nil {
return r, err
}
err = yaml.Unmarshal(responseBytes, &r)
if err != nil {
return r, fmt.Errorf("response body yaml unmarshal error: %s, type: %s, response body: %s", err.Error(), reflect.TypeOf(r).String(), string(responseBytes))
}
return r, nil
}
}
func JsonResponseHandler[Response any](readResponseOnStatusCodeIn ...int) ResponseHandler[Response] {
return func(httpResponse *http.Response) (Response, error) {
var r Response
responseBytes, err := BytesResponseHandler(readResponseOnStatusCodeIn...)(httpResponse)
if err != nil {
return r, err
}
err = json.Unmarshal(responseBytes, &r)
if err != nil {
return r, fmt.Errorf("response body json unmarshal error: %s, type: %s, response body: %s", err.Error(), reflect.TypeOf(r).String(), string(responseBytes))
}
return r, nil
}
}