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 log "github.com/sirupsen/logrus"
34 httpClient *http.Client
37 func New(httpClient *http.Client) *Client {
39 httpClient: httpClient,
43 func (c *Client) Get(path string, v interface{}) error {
44 req, err := c.newRequest(http.MethodGet, path, nil)
46 return fmt.Errorf("failed to create GET request: %w", err)
49 if err := c.doRequest(req, v); err != nil {
56 func (c *Client) Post(path string, payload interface{}, v interface{}) error {
58 s, _ := json.MarshalIndent(payload, "", "\t")
59 log.Debugf("Post request payload: " + string(s))
61 req, err := c.newRequest(http.MethodPost, path, payload)
63 return fmt.Errorf("failed to create POST request: %w", err)
66 if err := c.doRequest(req, v); err != nil {
73 func (c *Client) newRequest(method, path string, payload interface{}) (*http.Request, error) {
76 bodyBytes, err := json.Marshal(payload)
78 return nil, fmt.Errorf("failed to marshal request body: %w", err)
80 reqBody = bytes.NewReader(bodyBytes)
83 req, err := http.NewRequest(method, path, reqBody)
85 return nil, fmt.Errorf("failed to create HTTP request: %w", err)
89 req.Header.Set("Content-Type", "application/json; charset=utf-8")
91 log.Debugf("Http Client Request: [%s:%s]\n", req.Method, req.URL)
95 func (c *Client) doRequest(r *http.Request, v interface{}) error {
104 defer resp.Body.Close()
110 dec := json.NewDecoder(resp.Body)
111 if err := dec.Decode(v); err != nil {
112 return fmt.Errorf("could not parse response body: %w [%s:%s]", err, r.Method, r.URL.String())
114 log.Debugf("Http Client Response: %v\n", v)
118 func (c *Client) do(r *http.Request) (*http.Response, error) {
119 resp, err := c.httpClient.Do(r)
121 return nil, fmt.Errorf("failed to make request [%s:%s]: %w", r.Method, r.URL.String(), err)
124 if resp.StatusCode >= http.StatusOK && resp.StatusCode <= 299 {
128 defer resp.Body.Close()
130 return resp, fmt.Errorf("failed to do request, %d status code received", resp.StatusCode)