github.com/wtfutil/wtf@v0.43.0/modules/circleci/client.go (about) 1 package circleci 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "net/http" 8 "net/url" 9 10 "github.com/wtfutil/wtf/utils" 11 ) 12 13 type Client struct { 14 apiKey string 15 } 16 17 func NewClient(apiKey string) *Client { 18 client := Client{ 19 apiKey: apiKey, 20 } 21 22 return &client 23 } 24 25 func (client *Client) BuildsFor() ([]*Build, error) { 26 builds := []*Build{} 27 28 resp, err := client.circleRequest("recent-builds") 29 if err != nil { 30 return builds, err 31 } 32 33 err = utils.ParseJSON(&builds, bytes.NewReader(resp)) 34 if err != nil { 35 return builds, err 36 } 37 38 return builds, nil 39 } 40 41 /* -------------------- Unexported Functions -------------------- */ 42 43 var ( 44 circleAPIURL = &url.URL{Scheme: "https", Host: "circleci.com", Path: "/api/v1/"} 45 ) 46 47 func (client *Client) circleRequest(path string) ([]byte, error) { 48 params := url.Values{} 49 params.Add("circle-token", client.apiKey) 50 51 url := circleAPIURL.ResolveReference(&url.URL{Path: path, RawQuery: params.Encode()}) 52 53 req, err := http.NewRequest("GET", url.String(), http.NoBody) 54 req.Header.Add("Accept", "application/json") 55 req.Header.Add("Content-Type", "application/json") 56 if err != nil { 57 return nil, err 58 } 59 60 httpClient := &http.Client{} 61 resp, err := httpClient.Do(req) 62 if err != nil { 63 return nil, err 64 } 65 66 defer func() { _ = resp.Body.Close() }() 67 68 if resp.StatusCode < 200 || resp.StatusCode > 299 { 69 return nil, fmt.Errorf(resp.Status) 70 } 71 72 body, err := io.ReadAll(resp.Body) 73 if err != nil { 74 return nil, err 75 } 76 return body, nil 77 }