-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsonar_client.go
85 lines (73 loc) · 2.05 KB
/
sonar_client.go
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
78
79
80
81
82
83
84
85
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
)
type SonarClient struct {
c *http.Client
url string
user string
password string
}
func NewSonarClient(url, user, password string) *SonarClient {
return &SonarClient{url: strings.TrimRight(url, "/"), user: user, password: password, c: http.DefaultClient}
}
func (s *SonarClient) GetComponents() ([]*ComponentInfo, error) {
var c Components
err := s.executeGet(fmt.Sprintf("%s/api/components/search?qualifiers=TRK", s.url), &c)
if err != nil {
return nil, err
}
return c.Components, err
}
func (s *SonarClient) GetComponent(key string) (*Component, error) {
var c struct {
Component *Component `json:"component,omitempty"`
}
return c.Component, s.executeGet(fmt.Sprintf("%s/api/components/show?component=%s", s.url, key), &c)
}
func (s *SonarClient) GetMetrics() ([]*Metric, error) {
var m Metrics
err := s.executeGet(fmt.Sprintf("%s/api/metrics/search", s.url), &m)
if err != nil {
return nil, err
}
return m.Metrics, err
}
func (s *SonarClient) GetMeasures(key string, metrics []string) (*Measures, error) {
var m Measures
err := s.executeGet(fmt.Sprintf("%s/api/measures/component?component=%s&metricKeys=%s", s.url, key, strings.Join(metrics, ",")), &m)
if err != nil {
return nil, err
}
return &m, err
}
func (s *SonarClient) executeGet(u string, res interface{}) error {
rq, err := http.NewRequestWithContext(context.Background(), http.MethodGet, u, nil)
if err != nil {
return fmt.Errorf("unable to build request: %w", err)
}
rq.SetBasicAuth(s.user, s.password)
log.Printf("GET [%s]", rq.URL.String())
rs, err := s.c.Do(rq)
if err != nil {
return fmt.Errorf("unable to execute request: %w", err)
}
defer func() {
if rs.Body != nil {
if err := rs.Body.Close(); err != nil {
log.Print(err)
}
}
}()
if rs.StatusCode >= 400 {
body, _ := ioutil.ReadAll(rs.Body)
return fmt.Errorf("request failed. status code %d. Error: %s", rs.StatusCode, string(body))
}
return json.NewDecoder(rs.Body).Decode(res)
}