e9d3469d2fb9bbba52c05adca9278f21949621d8
[nonrtric/plt/sme.git] / capifcore / internal / restclient / HTTPClient.go
1 // -
2 //   ========================LICENSE_START=================================
3 //   O-RAN-SC
4 //   %%
5 //   Copyright (C) 2021: Nordix Foundation
6 //   %%
7 //   Licensed under the Apache License, Version 2.0 (the "License");
8 //   you may not use this file except in compliance with the License.
9 //   You may obtain a copy of the License at
10 //
11 //        http://www.apache.org/licenses/LICENSE-2.0
12 //
13 //   Unless required by applicable law or agreed to in writing, software
14 //   distributed under the License is distributed on an "AS IS" BASIS,
15 //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 //   See the License for the specific language governing permissions and
17 //   limitations under the License.
18 //   ========================LICENSE_END===================================
19 //
20
21 package restclient
22
23 import (
24         "bytes"
25         "fmt"
26         "io"
27         "net/http"
28 )
29
30 const ContentTypeJSON = "application/json"
31 const ContentTypePlain = "text/plain"
32
33 //go:generate mockery --name HTTPClient
34 type HTTPClient interface {
35         Do(*http.Request) (*http.Response, error)
36         Get(url string) (*http.Response, error)
37 }
38
39 type RequestError struct {
40         StatusCode int
41         Body       []byte
42 }
43
44 func (pe RequestError) Error() string {
45         return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", pe.StatusCode, string(pe.Body))
46 }
47
48 func Get(url string, header map[string]string, client HTTPClient) ([]byte, error) {
49         return do(http.MethodGet, url, nil, header, client)
50 }
51
52 func Put(url string, body []byte, client HTTPClient) error {
53         var header = map[string]string{"Content-Type": ContentTypeJSON}
54         _, err := do(http.MethodPut, url, body, header, client)
55         return err
56 }
57
58 func Post(url string, body []byte, header map[string]string, client HTTPClient) error {
59         _, err := do(http.MethodPost, url, body, header, client)
60         return err
61 }
62
63 func do(method string, url string, body []byte, header map[string]string, client HTTPClient) ([]byte, error) {
64         if req, reqErr := http.NewRequest(method, url, nil); reqErr == nil {
65                 if len(header) > 0 {
66                         setHeader(req, header)
67                 }
68                 if body != nil {
69                         req.Body = io.NopCloser(bytes.NewReader(body))
70                 }
71
72                 if response, respErr := client.Do(req); respErr == nil {
73                         if isResponseSuccess(response.StatusCode) {
74                                 fmt.Printf("HTTP client:: response statuscode:: %v body:: %v\n", response.StatusCode, response.Body)
75                                 defer response.Body.Close()
76
77                                 // Read the response body
78                                 respBody, err := io.ReadAll(response.Body)
79                                 if err != nil {
80                                         return nil, err
81                                 }
82                                 return respBody, nil
83                         } else {
84                                 return nil, getRequestError(response)
85                         }
86                 } else {
87                         return nil, respErr
88                 }
89         } else {
90                 return nil, reqErr
91         }
92 }
93
94 func setHeader(req *http.Request, header map[string]string) {
95         for key, element := range header {
96                 req.Header.Set(key, element)
97         }
98 }
99
100 func isResponseSuccess(statusCode int) bool {
101         return statusCode >= http.StatusOK && statusCode <= 299
102 }
103
104 func getRequestError(response *http.Response) RequestError {
105         defer response.Body.Close()
106         responseData, _ := io.ReadAll(response.Body)
107         putError := RequestError{
108                 StatusCode: response.StatusCode,
109                 Body:       responseData,
110         }
111         return putError
112 }