github.com/wtfutil/wtf@v0.43.0/modules/newrelic/client/http_helper.go (about) 1 package newrelic 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "net/http" 8 "net/url" 9 "strconv" 10 "strings" 11 "time" 12 ) 13 14 func (c *Client) doGet(path string, params fmt.Stringer, out interface{}) error { 15 var s string 16 if params != nil { 17 s = params.String() 18 } 19 r := strings.NewReader(s) 20 req, err := http.NewRequest("GET", c.url.String()+path, r) 21 if err != nil { 22 return err 23 } 24 req.Header.Add("X-Api-Key", c.apiKey) 25 req.Header.Add("Content-Type", "application/x-www-form-urlencoded") 26 return c.doRequest(req, out) 27 } 28 29 func (c *Client) doRequest(req *http.Request, out interface{}) error { 30 resp, err := c.httpClient.Do(req) 31 if err != nil { 32 return err 33 } 34 defer func() { _ = resp.Body.Close() }() 35 b, err := io.ReadAll(resp.Body) 36 if err != nil { 37 return err 38 } 39 if resp.StatusCode != 200 { 40 return fmt.Errorf("newrelic http error (%s): %s", resp.Status, b) 41 } 42 if len(b) == 0 { 43 b = []byte{'{', '}'} 44 } 45 err = json.Unmarshal(b, &out) 46 if err != nil { 47 return err 48 } 49 return nil 50 } 51 52 func encodeGetParams(params map[string]interface{}) string { 53 s := url.Values{} 54 for k, v := range params { 55 switch val := v.(type) { 56 case string: 57 if val != "" { 58 s.Add(k, val) 59 } 60 case int: 61 if val != 0 { 62 s.Add(k, strconv.Itoa(val)) 63 } 64 case []string: 65 if len(val) != 0 { 66 s.Add(k, strings.Join(val, ",")) 67 } 68 case []int: 69 arr := []string{} 70 for _, v := range val { 71 arr = append(arr, strconv.Itoa(v)) 72 } 73 if len(arr) != 0 { 74 s.Add(k, strings.Join(arr, ",")) 75 } 76 case time.Time: 77 if !val.IsZero() { 78 s.Add(k, val.String()) 79 } 80 case Array: 81 for _, v := range val.arr { 82 s.Add(k, v) 83 } 84 case bool: 85 s.Add(k, "true") 86 default: 87 s.Add(k, fmt.Sprintf("%v", v)) 88 } 89 } 90 return s.Encode() 91 }