Skip to content

Commit

Permalink
feature: add DoHTTPRequest generic method (#57)
Browse files Browse the repository at this point in the history
* feature: add DoHTTPRequest generic method

* fix

* fix
  • Loading branch information
atjhoendz authored Oct 9, 2023
1 parent 232ad8e commit 12cfd1c
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
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()
}()

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
}

0 comments on commit 12cfd1c

Please sign in to comment.