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===================================
31 type RequestError struct {
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))
40 // HTTPClient interface
41 type HTTPClient interface {
42 Get(url string) (*http.Response, error)
44 Do(*http.Request) (*http.Response, error)
52 Client = &http.Client{
53 Timeout: time.Second * 5,
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
67 return nil, getResponseError(response)
74 func PutWithoutAuth(url string, body []byte) error {
75 return do(http.MethodPut, url, body)
78 func Put(url string, body string, userName string, password string) error {
79 return do(http.MethodPut, url, []byte(body), userName, password)
82 func Delete(url string) error {
83 return do(http.MethodDelete, url, nil)
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 {
89 req.Header.Set("Content-Type", "application/json; charset=utf-8")
91 if len(userInfo) > 0 {
92 req.SetBasicAuth(userInfo[0], userInfo[1])
94 if response, respErr := Client.Do(req); respErr == nil {
95 if isResponseSuccess(response.StatusCode) {
98 return getResponseError(response)
108 func isResponseSuccess(statusCode int) bool {
109 return statusCode >= http.StatusOK && statusCode <= 299
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,