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 const ContentTypeJSON = "application/json"
31 const ContentTypePlain = "text/plain"
33 //go:generate mockery --name HTTPClient
34 type HTTPClient interface {
35 Do(*http.Request) (*http.Response, error)
38 type RequestError struct {
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))
47 func Put(url string, body []byte, client HTTPClient) error {
48 var header = map[string]string{"Content-Type": ContentTypeJSON}
49 return do(http.MethodPut, url, body, header, client)
52 func Post(url string, body []byte, header map[string]string, client HTTPClient) error {
53 return do(http.MethodPost, url, body, header, client)
56 func do(method string, url string, body []byte, header map[string]string, client HTTPClient) error {
57 if req, reqErr := http.NewRequest(method, url, bytes.NewBuffer(body)); reqErr == nil {
59 setHeader(req, header)
61 if response, respErr := client.Do(req); respErr == nil {
62 if isResponseSuccess(response.StatusCode) {
65 return getRequestError(response)
75 func setHeader(req *http.Request, header map[string]string) {
76 for key, element := range header {
77 req.Header.Set(key, element)
81 func isResponseSuccess(statusCode int) bool {
82 return statusCode >= http.StatusOK && statusCode <= 299
85 func getRequestError(response *http.Response) RequestError {
86 defer response.Body.Close()
87 responseData, _ := io.ReadAll(response.Body)
88 putError := RequestError{
89 StatusCode: response.StatusCode,