ychacon | 7178971 | 2023-05-15 11:07:32 +0200 | [diff] [blame^] | 1 | // - |
| 2 | // |
| 3 | // ========================LICENSE_START================================= |
| 4 | // O-RAN-SC |
| 5 | // %% |
| 6 | // Copyright (C) 2023: Nordix Foundation |
| 7 | // %% |
| 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 |
| 11 | // |
| 12 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 13 | // |
| 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=================================== |
| 20 | package handler |
| 21 | |
| 22 | import ( |
| 23 | "fmt" |
| 24 | "io" |
| 25 | "net/http" |
| 26 | ) |
| 27 | |
| 28 | func makeRequest(method, url string, headers map[string]string, data io.Reader) ([]byte, error) { |
| 29 | client := &http.Client{} |
| 30 | |
| 31 | // Create a new HTTP request with the specified method and URL |
| 32 | req, err := http.NewRequest(method, url, nil) |
| 33 | if err != nil { |
| 34 | return nil, err |
| 35 | } |
| 36 | |
| 37 | // Set any headers specified in the headers map |
| 38 | for k, v := range headers { |
| 39 | req.Header.Set(k, v) |
| 40 | } |
| 41 | |
| 42 | // If there is data to send, marshal it to JSON and set it as the request body |
| 43 | if data != nil { |
| 44 | /*jsonBytes, err := json.Marshal(data) |
| 45 | if err != nil { |
| 46 | return nil, err |
| 47 | }*/ |
| 48 | req.Body = io.NopCloser(data) |
| 49 | } |
| 50 | |
| 51 | // Send the request and get the response |
| 52 | if resp, err := client.Do(req); err == nil { |
| 53 | if isResponseSuccess(resp.StatusCode) { |
| 54 | defer resp.Body.Close() |
| 55 | |
| 56 | // Read the response body |
| 57 | respBody, err := io.ReadAll(resp.Body) |
| 58 | if err != nil { |
| 59 | return nil, err |
| 60 | } |
| 61 | return respBody, nil |
| 62 | } else { |
| 63 | return nil, getRequestError(resp) |
| 64 | } |
| 65 | } else { |
| 66 | return nil, err |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | func isResponseSuccess(statusCode int) bool { |
| 71 | return statusCode >= http.StatusOK && statusCode <= 299 |
| 72 | } |
| 73 | |
| 74 | func getRequestError(response *http.Response) error { |
| 75 | defer response.Body.Close() |
| 76 | responseData, _ := io.ReadAll(response.Body) |
| 77 | |
| 78 | return fmt.Errorf("message: %v code: %v", string(responseData), response.StatusCode) |
| 79 | } |