github.com/netdata/go.d.plugin@v0.58.1/modules/bind/json_client.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package bind 4 5 import ( 6 "encoding/json" 7 "fmt" 8 "io" 9 "net/http" 10 "net/url" 11 "path" 12 13 "github.com/netdata/go.d.plugin/pkg/web" 14 ) 15 16 type serverStats = jsonServerStats 17 18 type jsonServerStats struct { 19 OpCodes map[string]int64 20 QTypes map[string]int64 21 NSStats map[string]int64 22 SockStats map[string]int64 23 Views map[string]jsonView 24 } 25 26 type jsonView struct { 27 Resolver jsonViewResolver 28 } 29 30 type jsonViewResolver struct { 31 Stats map[string]int64 32 QTypes map[string]int64 33 CacheStats map[string]int64 34 } 35 36 func newJSONClient(client *http.Client, request web.Request) *jsonClient { 37 return &jsonClient{httpClient: client, request: request} 38 } 39 40 type jsonClient struct { 41 httpClient *http.Client 42 request web.Request 43 } 44 45 func (c jsonClient) serverStats() (*serverStats, error) { 46 req := c.request.Copy() 47 u, err := url.Parse(req.URL) 48 if err != nil { 49 return nil, fmt.Errorf("error on parsing URL: %v", err) 50 } 51 52 u.Path = path.Join(u.Path, "/server") 53 req.URL = u.String() 54 55 httpReq, err := web.NewHTTPRequest(req) 56 if err != nil { 57 return nil, fmt.Errorf("error on creating HTTP request: %v", err) 58 } 59 60 resp, err := c.httpClient.Do(httpReq) 61 if err != nil { 62 return nil, fmt.Errorf("error on request : %v", err) 63 } 64 defer closeBody(resp) 65 66 if resp.StatusCode != http.StatusOK { 67 return nil, fmt.Errorf("%s returned HTTP status %d", httpReq.URL, resp.StatusCode) 68 } 69 70 stats := &jsonServerStats{} 71 if err = json.NewDecoder(resp.Body).Decode(stats); err != nil { 72 return nil, fmt.Errorf("error on decoding response from %s : %v", httpReq.URL, err) 73 } 74 return stats, nil 75 } 76 77 func closeBody(resp *http.Response) { 78 if resp != nil && resp.Body != nil { 79 _, _ = io.Copy(io.Discard, resp.Body) 80 _ = resp.Body.Close() 81 } 82 }