3 // ========================LICENSE_START=================================
6 // Copyright (C) 2023: Nordix Foundation
8 // Licensed under the Apache License, Version 2.0 (the "License");
9 // you may not use this file except in compliance with the License.
10 // You may obtain a copy of the License at
12 // http://www.apache.org/licenses/LICENSE-2.0
14 // Unless required by applicable law or agreed to in writing, software
15 // distributed under the License is distributed on an "AS IS" BASIS,
16 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 // See the License for the specific language governing permissions and
18 // limitations under the License.
19 // ========================LICENSE_END===================================
30 func makeRequest(method, url string, headers map[string]string, data interface{}) ([]byte, error) {
31 client := &http.Client{}
33 // Create a new HTTP request with the specified method and URL
34 req, err := http.NewRequest(method, url, nil)
39 // Set any headers specified in the headers map
40 for k, v := range headers {
44 // If there is data to send, marshal it to JSON and set it as the request body
46 jsonBytes, err := json.Marshal(data)
50 req.Body = io.NopCloser(bytes.NewReader(jsonBytes))
53 // Send the request and get the response
54 if resp, err := client.Do(req); err == nil {
55 if isResponseSuccess(resp.StatusCode) {
56 defer resp.Body.Close()
58 // Read the response body
59 respBody, err := io.ReadAll(resp.Body)
65 return nil, getRequestError(resp)
72 func isResponseSuccess(statusCode int) bool {
73 return statusCode >= http.StatusOK && statusCode <= 299
76 func getRequestError(response *http.Response) error {
77 defer response.Body.Close()
78 responseData, _ := io.ReadAll(response.Body)
80 return fmt.Errorf("message: %v code: %v", string(responseData), response.StatusCode)