2 // ========================LICENSE_START=================================
5 // Copyright (C) 2021: Nordix Foundation
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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===================================
30 // HTTPClient interface
31 type HTTPClient interface {
32 Get(url string) (*http.Response, error)
34 Do(*http.Request) (*http.Response, error)
37 type RequestError struct {
42 func (pe RequestError) Error() string {
43 return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", pe.StatusCode, string(pe.Body))
51 Client = &http.Client{}
54 func Get(url string) ([]byte, error) {
55 if response, err := Client.Get(url); err == nil {
56 defer response.Body.Close()
57 if responseData, err := io.ReadAll(response.Body); err == nil {
58 if isResponseSuccess(response.StatusCode) {
59 return responseData, nil
61 requestError := RequestError{
62 StatusCode: response.StatusCode,
65 return nil, requestError
75 func Put(url string, body []byte) error {
76 if req, reqErr := http.NewRequest(http.MethodPut, url, bytes.NewBuffer(body)); reqErr == nil {
77 req.Header.Set("Content-Type", "application/json; charset=utf-8")
78 if response, respErr := Client.Do(req); respErr == nil {
79 if isResponseSuccess(response.StatusCode) {
82 return getRequestError(response)
92 func isResponseSuccess(statusCode int) bool {
93 return statusCode >= http.StatusOK && statusCode <= 299
96 func getRequestError(response *http.Response) RequestError {
97 defer response.Body.Close()
98 responseData, _ := io.ReadAll(response.Body)
99 putError := RequestError{
100 StatusCode: response.StatusCode,