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 type RequestError struct {
35 func (e RequestError) Error() string {
36 return fmt.Sprintf("Request failed due to error response with status: %v and body: %v", e.StatusCode, string(e.Body))
39 // HTTPClient interface
40 type HTTPClient interface {
41 Get(url string) (*http.Response, error)
43 Do(*http.Request) (*http.Response, error)
46 func PutWithoutAuth(url string, body []byte, client HTTPClient) error {
47 return do(http.MethodPut, url, body, client)
50 func Put(url string, body string, client HTTPClient, userName string, password string) error {
51 return do(http.MethodPut, url, []byte(body), client, userName, password)
54 func Delete(url string, client HTTPClient) error {
55 return do(http.MethodDelete, url, nil, client)
58 func do(method string, url string, body []byte, client HTTPClient, userInfo ...string) error {
59 if req, reqErr := http.NewRequest(method, url, bytes.NewBuffer(body)); reqErr == nil {
61 req.Header.Set("Content-Type", "application/json; charset=utf-8")
63 if len(userInfo) > 0 {
64 req.SetBasicAuth(userInfo[0], userInfo[1])
66 if response, respErr := client.Do(req); respErr == nil {
67 if isResponseSuccess(response.StatusCode) {
70 return getResponseError(response)
80 func isResponseSuccess(statusCode int) bool {
81 return statusCode >= http.StatusOK && statusCode <= 299
84 func getResponseError(response *http.Response) RequestError {
85 defer response.Body.Close()
86 responseData, _ := io.ReadAll(response.Body)
87 putError := RequestError{
88 StatusCode: response.StatusCode,