de0ad1d0ca26706802f1b598126f7d44beb18d82
[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 }
37
38 type RequestError struct {
39         StatusCode int
40         Body       []byte
41 }
42
43 func (pe RequestError) Error() string {
44         return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", pe.StatusCode, string(pe.Body))
45 }
46
47 func Put(url string, body []byte, client HTTPClient) error {
48         return do(http.MethodPut, url, body, ContentTypeJSON, client)
49 }
50
51 func do(method string, url string, body []byte, contentType string, client HTTPClient) error {
52         if req, reqErr := http.NewRequest(method, url, bytes.NewBuffer(body)); reqErr == nil {
53                 req.Header.Set("Content-Type", contentType)
54                 if response, respErr := client.Do(req); respErr == nil {
55                         if isResponseSuccess(response.StatusCode) {
56                                 return nil
57                         } else {
58                                 return getRequestError(response)
59                         }
60                 } else {
61                         return respErr
62                 }
63         } else {
64                 return reqErr
65         }
66 }
67
68 func isResponseSuccess(statusCode int) bool {
69         return statusCode >= http.StatusOK && statusCode <= 299
70 }
71
72 func getRequestError(response *http.Response) RequestError {
73         defer response.Body.Close()
74         responseData, _ := io.ReadAll(response.Body)
75         putError := RequestError{
76                 StatusCode: response.StatusCode,
77                 Body:       responseData,
78         }
79         return putError
80 }