github.com/netdata/go.d.plugin@v0.58.1/modules/phpdaemon/client.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package phpdaemon 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 type decodeFunc func(dst interface{}, reader io.Reader) error 15 16 func decodeJson(dst interface{}, reader io.Reader) error { return json.NewDecoder(reader).Decode(dst) } 17 18 func newAPIClient(httpClient *http.Client, request web.Request) *client { 19 return &client{ 20 httpClient: httpClient, 21 request: request, 22 } 23 } 24 25 type client struct { 26 httpClient *http.Client 27 request web.Request 28 } 29 30 func (c *client) queryFullStatus() (*FullStatus, error) { 31 var status FullStatus 32 err := c.doWithDecode(&status, decodeJson, c.request) 33 if err != nil { 34 return nil, err 35 } 36 37 return &status, nil 38 } 39 40 func (c *client) doWithDecode(dst interface{}, decode decodeFunc, request web.Request) error { 41 req, err := web.NewHTTPRequest(request) 42 if err != nil { 43 return fmt.Errorf("error on creating http request to %s : %v", request.URL, err) 44 } 45 46 resp, err := c.doOK(req) 47 defer closeBody(resp) 48 if err != nil { 49 return err 50 } 51 52 if err = decode(dst, resp.Body); err != nil { 53 return fmt.Errorf("error on parsing response from %s : %v", req.URL, err) 54 } 55 56 return nil 57 } 58 59 func (c client) doOK(req *http.Request) (*http.Response, error) { 60 resp, err := c.httpClient.Do(req) 61 if err != nil { 62 return resp, fmt.Errorf("error on request : %v", err) 63 } 64 65 if resp.StatusCode != http.StatusOK { 66 return resp, fmt.Errorf("%s returned HTTP status %d", req.URL, resp.StatusCode) 67 } 68 69 return resp, err 70 } 71 72 func closeBody(resp *http.Response) { 73 if resp != nil && resp.Body != nil { 74 _, _ = io.Copy(io.Discard, resp.Body) 75 _ = resp.Body.Close() 76 } 77 }