Add test for consumer restclient
[nonrtric.git] / test / usecases / oruclosedlooprecovery / goversion / internal / restclient / client.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         "time"
29 )
30
31 type RequestError struct {
32         StatusCode int
33         Body       []byte
34 }
35
36 func (pe RequestError) Error() string {
37         return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", pe.StatusCode, string(pe.Body))
38 }
39
40 // HTTPClient interface
41 type HTTPClient interface {
42         Get(url string) (*http.Response, error)
43
44         Do(*http.Request) (*http.Response, error)
45 }
46
47 var (
48         Client HTTPClient
49 )
50
51 func init() {
52         Client = &http.Client{
53                 Timeout: time.Second * 5,
54         }
55 }
56
57 func Get(url string) ([]byte, error) {
58         if response, err := Client.Get(url); err == nil {
59                 if isResponseSuccess(response.StatusCode) {
60                         defer response.Body.Close()
61                         if responseData, err := io.ReadAll(response.Body); err == nil {
62                                 return responseData, nil
63                         } else {
64                                 return nil, err
65                         }
66                 } else {
67                         return nil, getResponseError(response)
68                 }
69         } else {
70                 return nil, err
71         }
72 }
73
74 func PutWithoutAuth(url string, body []byte) error {
75         return do(http.MethodPut, url, body)
76 }
77
78 func Put(url string, body string, userName string, password string) error {
79         return do(http.MethodPut, url, []byte(body), userName, password)
80 }
81
82 func Delete(url string) error {
83         return do(http.MethodDelete, url, nil)
84 }
85
86 func do(method string, url string, body []byte, userInfo ...string) error {
87         if req, reqErr := http.NewRequest(method, url, bytes.NewBuffer(body)); reqErr == nil {
88                 if body != nil {
89                         req.Header.Set("Content-Type", "application/json; charset=utf-8")
90                 }
91                 if len(userInfo) > 0 {
92                         req.SetBasicAuth(userInfo[0], userInfo[1])
93                 }
94                 if response, respErr := Client.Do(req); respErr == nil {
95                         if isResponseSuccess(response.StatusCode) {
96                                 return nil
97                         } else {
98                                 return getResponseError(response)
99                         }
100                 } else {
101                         return respErr
102                 }
103         } else {
104                 return reqErr
105         }
106 }
107
108 func isResponseSuccess(statusCode int) bool {
109         return statusCode >= http.StatusOK && statusCode <= 299
110 }
111
112 func getResponseError(response *http.Response) RequestError {
113         defer response.Body.Close()
114         responseData, _ := io.ReadAll(response.Body)
115         putError := RequestError{
116                 StatusCode: response.StatusCode,
117                 Body:       responseData,
118         }
119         return putError
120 }