MakeHTTPRequest fires an http request and returns a response
(ctx context.Context, request *HTTPRequest, vPtr interface{})
| 26 | |
| 27 | // MakeHTTPRequest fires an http request and returns a response |
| 28 | func MakeHTTPRequest(ctx context.Context, request *HTTPRequest, vPtr interface{}) (int, error) { |
| 29 | // Make a request object |
| 30 | req, err := http.NewRequestWithContext(ctx, request.Method, request.URL, request.Params) |
| 31 | if err != nil { |
| 32 | return http.StatusInternalServerError, helpers.Logger.LogError(helpers.GetRequestID(ctx), fmt.Sprintf("Unable to create http request for url (%s)", request.URL), err, nil) |
| 33 | } |
| 34 | |
| 35 | // Add the token only if its provided |
| 36 | if request.Token != "" { |
| 37 | req.Header.Add("Authorization", "Bearer "+request.Token) |
| 38 | } |
| 39 | |
| 40 | // Add the sc-token only if its provided |
| 41 | if request.SCToken != "" { |
| 42 | req.Header.Add("x-sc-token", "Bearer "+request.SCToken) |
| 43 | } |
| 44 | |
| 45 | // Add the remaining headers |
| 46 | if request.Headers != nil { |
| 47 | request.Headers.UpdateHeader(req.Header) |
| 48 | } |
| 49 | |
| 50 | // Create a http client and fire the request |
| 51 | client := &http.Client{} |
| 52 | |
| 53 | req = req.WithContext(ctx) |
| 54 | resp, err := client.Do(req) |
| 55 | if err != nil { |
| 56 | return http.StatusInternalServerError, helpers.Logger.LogError(helpers.GetRequestID(ctx), fmt.Sprintf("Unable to make http request for url (%s)", request.URL), err, nil) |
| 57 | } |
| 58 | defer CloseTheCloser(resp.Body) |
| 59 | |
| 60 | if resp.StatusCode != 204 { |
| 61 | if err := json.NewDecoder(resp.Body).Decode(vPtr); err != nil { |
| 62 | return resp.StatusCode, helpers.Logger.LogError(helpers.GetRequestID(ctx), fmt.Sprintf("Unable to json unmarshal response of http request url (%s)", request.URL), err, nil) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | return resp.StatusCode, nil |
| 67 | } |
| 68 | |
| 69 | // GetTokenFromHeader returns the token from the request header |
| 70 | func GetTokenFromHeader(r *http.Request) string { |
no test coverage detected