11package requester
22
33import (
4+ "bytes"
5+ "encoding/json"
46 "fmt"
57 "io"
68 "net/http"
@@ -36,7 +38,7 @@ func NewHTTPClient(opts ...HTTPOption) *HTTPClient {
3638 }
3739}
3840
39- func (c * HTTPClient ) Do (req * http.Request ) ([] byte , error ) {
41+ func (c * HTTPClient ) SendRequest (req * http.Request , response any , outputResponse bool ) (* http. Response , error ) {
4042 if err := c .before (req ); err != nil {
4143 return nil , err
4244 }
@@ -46,14 +48,77 @@ func (c *HTTPClient) Do(req *http.Request) ([]byte, error) {
4648 return nil , err
4749 }
4850
49- defer resp .Body .Close ()
50- body , err := io .ReadAll (resp .Body )
51+ if ! outputResponse {
52+ defer resp .Body .Close ()
53+ }
54+
55+ if c .IsFailureStatusCode (resp ) {
56+ return nil , fmt .Errorf ("http status not 2xx: %d" , resp .StatusCode )
57+ }
58+
59+ if outputResponse {
60+ var buf bytes.Buffer
61+ tee := io .TeeReader (resp .Body , & buf )
62+ err = DecodeResponse (tee , response )
63+
64+ resp .Body = io .NopCloser (& buf )
65+ } else {
66+ err = json .NewDecoder (resp .Body ).Decode (response )
67+ }
68+
69+ if err != nil {
70+ return nil , err
71+ }
72+
73+ return resp , nil
74+ }
75+
76+ func (c * HTTPClient ) SendRequestRaw (req * http.Request ) (* http.Response , error ) {
77+ if err := c .before (req ); err != nil {
78+ return nil , err
79+ }
80+
81+ resp , err := c .client .Do (req )
5182 if err != nil {
5283 return nil , err
5384 }
5485
55- if int (resp .StatusCode / 100 ) != 2 {
56- return nil , fmt .Errorf ("http status not 2xx: %d %s" , resp .StatusCode , string (body ))
86+ if c .IsFailureStatusCode (resp ) {
87+ return nil , fmt .Errorf ("http status not 2xx: %d" , resp .StatusCode )
88+ }
89+
90+ return resp , nil
91+ }
92+
93+ func (r * HTTPClient ) IsFailureStatusCode (resp * http.Response ) bool {
94+ return resp .StatusCode < http .StatusOK || resp .StatusCode >= http .StatusBadRequest
95+ }
96+
97+ type Stringer interface {
98+ GetString () * string
99+ }
100+
101+ func DecodeResponse (body io.Reader , v any ) error {
102+ if v == nil {
103+ return nil
104+ }
105+
106+ if result , ok := v .(* string ); ok {
107+ return DecodeString (body , result )
108+ }
109+
110+ if stringer , ok := v .(Stringer ); ok {
111+ return DecodeString (body , stringer .GetString ())
112+ }
113+
114+ return json .NewDecoder (body ).Decode (v )
115+ }
116+
117+ func DecodeString (body io.Reader , output * string ) error {
118+ b , err := io .ReadAll (body )
119+ if err != nil {
120+ return err
57121 }
58- return body , nil
122+ * output = string (b )
123+ return nil
59124}
0 commit comments