github.com/decred/politeia@v1.4.0/politeiawww/legacy/codetracker/github/api/api.go (about) 1 // Copyright (c) 2020 The Decred developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package api 6 7 import ( 8 "context" 9 "fmt" 10 "io" 11 "net/http" 12 "sync" 13 14 "golang.org/x/oauth2" 15 ) 16 17 // Client contains the http client that communicates with the Github 18 // servers, mutexes and api rate limiting rules. 19 type Client struct { 20 sync.Mutex 21 22 gh *http.Client 23 24 rateLimit RateLimitRule 25 } 26 27 // NewClient creates a new instance of Client that contains a authorized 28 // client with the provided token argument. 29 func NewClient(token string) *Client { 30 ts := oauth2.StaticTokenSource( 31 &oauth2.Token{ 32 AccessToken: token, 33 }) 34 gh := oauth2.NewClient(context.Background(), ts) 35 36 return &Client{ 37 gh: gh, 38 } 39 } 40 41 func (c *Client) sendGithubRequest(req *http.Request) ([]byte, error) { 42 c.RateLimit() 43 res, err := c.gh.Do(req) 44 if err != nil { 45 return nil, err 46 } 47 48 body, err := io.ReadAll(res.Body) 49 defer res.Body.Close() 50 if err != nil { 51 return nil, err 52 } 53 if res.StatusCode != http.StatusOK { 54 return nil, fmt.Errorf("http returned %v", res.StatusCode) 55 } 56 return body, nil 57 }