|
| 1 | +package github |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "errors" |
| 7 | + "io" |
| 8 | + "io/ioutil" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | +) |
| 12 | + |
| 13 | +type Github struct { |
| 14 | + client *http.Client |
| 15 | +} |
| 16 | + |
| 17 | +// NewGithub initialized Github |
| 18 | +func NewGithub(client *http.Client) *Github { |
| 19 | + return &Github{ |
| 20 | + client: client, |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +func withContext(ctx context.Context, req *http.Request) *http.Request { |
| 25 | + return req.WithContext(ctx) |
| 26 | +} |
| 27 | + |
| 28 | +// sanitizeURL redacts the client_secret parameter from the URL which may be |
| 29 | +// exposed to the user. |
| 30 | +func sanitizeURL(uri *url.URL) *url.URL { |
| 31 | + if uri == nil { |
| 32 | + return nil |
| 33 | + } |
| 34 | + params := uri.Query() |
| 35 | + if len(params.Get("client_secret")) > 0 { |
| 36 | + params.Set("client_secret", "REDACTED") |
| 37 | + uri.RawQuery = params.Encode() |
| 38 | + } |
| 39 | + return uri |
| 40 | +} |
| 41 | + |
| 42 | +// GetReadme returns readme content in HTML as well as in JSON format |
| 43 | +func (g *Github) GetReadme(ctx context.Context, owner string, repo string) (string, error) { |
| 44 | + u := fmt.Sprintf("repos/%v/%v/readme", owner, repo) |
| 45 | + |
| 46 | + req, err := http.NewRequest("GET", "https://api.github.com/"+u, nil) // TODO -- need to refactored |
| 47 | + req = withContext(ctx, req) |
| 48 | + req.Header.Add("Accept", "application/vnd.github.v3.html+json") |
| 49 | + resp, err := g.client.Do(req) |
| 50 | + if err != nil { |
| 51 | + // If we got an error, and the context has been canceled, |
| 52 | + // the context'g error is probably more useful. |
| 53 | + select { |
| 54 | + case <-ctx.Done(): |
| 55 | + return "", ctx.Err() |
| 56 | + default: |
| 57 | + } |
| 58 | + |
| 59 | + // If the error type is *url.Error, sanitize its URL before returning. |
| 60 | + if e, ok := err.(*url.Error); ok { |
| 61 | + if url, err := url.Parse(e.URL); err == nil { |
| 62 | + e.URL = sanitizeURL(url).String() |
| 63 | + return "", e |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return "", err |
| 68 | + } |
| 69 | + |
| 70 | + defer func() { |
| 71 | + // Drain up to 512 bytes and close the body to let the Transport reuse the connection |
| 72 | + io.CopyN(ioutil.Discard, resp.Body, 512) |
| 73 | + resp.Body.Close() |
| 74 | + }() |
| 75 | + |
| 76 | + if c := resp.StatusCode; 200 <= c && c <= 299 { |
| 77 | + data, err := ioutil.ReadAll(resp.Body) |
| 78 | + if err != nil { |
| 79 | + return "", err |
| 80 | + } |
| 81 | + return string(data[:]), nil |
| 82 | + } |
| 83 | + return "", errors.New(resp.Status) |
| 84 | +} |
0 commit comments