github.com/netdata/go.d.plugin@v0.58.1/modules/hdfs/client.go (about)

     1  // SPDX-License-Identifier: GPL-3.0-or-later
     2  
     3  package hdfs
     4  
     5  import (
     6  	"encoding/json"
     7  	"fmt"
     8  	"io"
     9  	"net/http"
    10  
    11  	"github.com/netdata/go.d.plugin/pkg/web"
    12  )
    13  
    14  func newClient(httpClient *http.Client, request web.Request) *client {
    15  	return &client{
    16  		httpClient: httpClient,
    17  		request:    request,
    18  	}
    19  }
    20  
    21  type client struct {
    22  	httpClient *http.Client
    23  	request    web.Request
    24  }
    25  
    26  func (c *client) do() (*http.Response, error) {
    27  	req, err := web.NewHTTPRequest(c.request)
    28  	if err != nil {
    29  		return nil, fmt.Errorf("error on creating http request to %s : %v", c.request.URL, err)
    30  	}
    31  
    32  	// req.Header.Add("Accept-Encoding", "gzip")
    33  	// req.Header.Set("User-Agent", "netdata/go.d.plugin")
    34  
    35  	return c.httpClient.Do(req)
    36  }
    37  
    38  func (c *client) doOK() (*http.Response, error) {
    39  	resp, err := c.do()
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	if resp.StatusCode != http.StatusOK {
    45  		return resp, fmt.Errorf("%s returned %d", c.request.URL, resp.StatusCode)
    46  	}
    47  	return resp, nil
    48  }
    49  
    50  func (c *client) doOKWithDecodeJSON(dst interface{}) error {
    51  	resp, err := c.doOK()
    52  	defer closeBody(resp)
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	err = json.NewDecoder(resp.Body).Decode(dst)
    58  	if err != nil {
    59  		return fmt.Errorf("error on decoding response from %s : %v", c.request.URL, err)
    60  	}
    61  	return nil
    62  }
    63  
    64  func closeBody(resp *http.Response) {
    65  	if resp != nil && resp.Body != nil {
    66  		_, _ = io.Copy(io.Discard, resp.Body)
    67  		_ = resp.Body.Close()
    68  	}
    69  }