summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/phpdaemon/client.go
blob: 7a8c5969f36d13b86f66a71f4cae4289c39027f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// SPDX-License-Identifier: GPL-3.0-or-later

package phpdaemon

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"github.com/netdata/netdata/go/go.d.plugin/pkg/web"
)

type decodeFunc func(dst interface{}, reader io.Reader) error

func decodeJson(dst interface{}, reader io.Reader) error { return json.NewDecoder(reader).Decode(dst) }

func newAPIClient(httpClient *http.Client, request web.Request) *client {
	return &client{
		httpClient: httpClient,
		request:    request,
	}
}

type client struct {
	httpClient *http.Client
	request    web.Request
}

func (c *client) queryFullStatus() (*FullStatus, error) {
	var status FullStatus
	err := c.doWithDecode(&status, decodeJson, c.request)
	if err != nil {
		return nil, err
	}

	return &status, nil
}

func (c *client) doWithDecode(dst interface{}, decode decodeFunc, request web.Request) error {
	req, err := web.NewHTTPRequest(request)
	if err != nil {
		return fmt.Errorf("error on creating http request to %s : %v", request.URL, err)
	}

	resp, err := c.doOK(req)
	defer closeBody(resp)
	if err != nil {
		return err
	}

	if err = decode(dst, resp.Body); err != nil {
		return fmt.Errorf("error on parsing response from %s : %v", req.URL, err)
	}

	return nil
}

func (c client) doOK(req *http.Request) (*http.Response, error) {
	resp, err := c.httpClient.Do(req)
	if err != nil {
		return resp, fmt.Errorf("error on request : %v", err)
	}

	if resp.StatusCode != http.StatusOK {
		return resp, fmt.Errorf("%s returned HTTP status %d", req.URL, resp.StatusCode)
	}

	return resp, err
}

func closeBody(resp *http.Response) {
	if resp != nil && resp.Body != nil {
		_, _ = io.Copy(io.Discard, resp.Body)
		_ = resp.Body.Close()
	}
}