75 lines
1.9 KiB
Go
75 lines
1.9 KiB
Go
package httpClient
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
func (t *HttpClient) DefaultRequest(
|
|
ctx context.Context, acceptStatus int,
|
|
uri, httpMethod string,
|
|
body, result interface{},
|
|
queryParams map[string]string,
|
|
) (*int, error) {
|
|
op := "httpClient/DefaultRequest"
|
|
|
|
var req *http.Request
|
|
var err error
|
|
url := fmt.Sprintf("%v%v", t.endpoint, uri)
|
|
|
|
if body != nil {
|
|
bodyBytes, err := json.Marshal(body)
|
|
if err != nil {
|
|
t.logger.Error(fmt.Sprintf("%v: %v", op, err.Error()))
|
|
return nil, fmt.Errorf("failed to marshal request body")
|
|
}
|
|
req, err = http.NewRequest(httpMethod, url, bytes.NewReader(bodyBytes))
|
|
} else {
|
|
req, err = http.NewRequest(httpMethod, url, nil)
|
|
}
|
|
t.logger.Info(fmt.Sprintf("Sending a request %v %v", httpMethod, url))
|
|
|
|
if err != nil {
|
|
t.logger.Error(fmt.Sprintf("%v: %v", op, err.Error()))
|
|
return nil, fmt.Errorf("failed to create request")
|
|
}
|
|
|
|
req.Header.Set("Authorization", "Bearer "+t.token)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Accept", "application/json")
|
|
if queryParams != nil {
|
|
q := req.URL.Query()
|
|
for key, value := range queryParams {
|
|
q.Add(key, value)
|
|
}
|
|
req.URL.RawQuery = q.Encode()
|
|
}
|
|
|
|
resp, err := t.client.Do(req)
|
|
if err != nil || resp == nil {
|
|
t.logger.Error(fmt.Sprintf("%v: %v", op, err.Error()))
|
|
return nil, fmt.Errorf("failed to perform request")
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != acceptStatus {
|
|
var errMsg interface{}
|
|
json.NewDecoder(resp.Body).Decode(&errMsg)
|
|
t.logger.Error(fmt.Sprintf("%v: %v", op, errMsg))
|
|
return &resp.StatusCode, fmt.Errorf("an error occurred while processing the response")
|
|
}
|
|
|
|
if result == nil {
|
|
return &resp.StatusCode, nil
|
|
}
|
|
|
|
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
|
|
t.logger.Error(fmt.Sprintf("%v: %v", op, err.Error()))
|
|
return &resp.StatusCode, fmt.Errorf("failed to decode response")
|
|
}
|
|
return &resp.StatusCode, nil
|
|
}
|