-
Notifications
You must be signed in to change notification settings - Fork 4
/
http.go
50 lines (42 loc) · 1.16 KB
/
http.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
package utils
import (
"context"
"encoding/json"
"io"
"net/http"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context/ctxhttp"
)
type httpResponse interface {
IsHTTPResponse()
}
// DoHTTPRequest generic do http request using ctxhttp
func DoHTTPRequest[T httpResponse](ctx context.Context, httpClient *http.Client, httpRequest *http.Request) (respStatusCode int, respBody *T, err error) {
logger := log.WithFields(log.Fields{
"ctx": DumpIncomingContext(ctx),
"httpRequest": Dump(httpRequest),
})
httpResp, err := ctxhttp.Do(ctx, httpClient, httpRequest)
if err != nil {
logger.Error(err)
return respStatusCode, nil, err
}
respInBytes, err := io.ReadAll(httpResp.Body)
if err != nil {
logger.Error(err)
return httpResp.StatusCode, nil, err
}
defer func() {
_ = httpResp.Body.Close()
}()
if httpResp.StatusCode != http.StatusOK {
logger.WithField("body", string(respInBytes)).Warn("http status code is not ok")
}
var resp T
err = json.Unmarshal(respInBytes, &resp)
if err != nil {
logger.WithField("respInBytes", string(respInBytes)).Error(err)
return httpResp.StatusCode, nil, err
}
return httpResp.StatusCode, &resp, nil
}