MCPcopy
hub / github.com/spacecloud-io/space-cloud / MakeHTTPRequest

Function MakeHTTPRequest

gateway/utils/http.go:28–67  ·  view source on GitHub ↗

MakeHTTPRequest fires an http request and returns a response

(ctx context.Context, request *HTTPRequest, vPtr interface{})

Source from the content-addressed store, hash-verified

26
27// MakeHTTPRequest fires an http request and returns a response
28func 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
70func GetTokenFromHeader(r *http.Request) string {

Callers 1

matchFuncMethod · 0.85

Calls 4

AddMethod · 0.80
CloseTheCloserFunction · 0.70
UpdateHeaderMethod · 0.65
DoMethod · 0.65

Tested by

no test coverage detected