|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "io/ioutil" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + API_URL = "https://api.github.com" |
| 14 | +) |
| 15 | + |
| 16 | +/* create a new request that sends the auth token */ |
| 17 | +func NewAuthRequest(method, url, bodyType, token string, body io.Reader) (*http.Request, error) { |
| 18 | + vprintln("creating request:", method, url, bodyType, token) |
| 19 | + |
| 20 | + req, err := http.NewRequest(method, url, body) |
| 21 | + if err != nil { |
| 22 | + return nil, err |
| 23 | + } |
| 24 | + |
| 25 | + if body != nil { |
| 26 | + switch v := body.(type) { |
| 27 | + case *os.File: |
| 28 | + /* apparently chunking doesnt work yet... |
| 29 | + * vprintln("OS.FILE detected, chunking!", v) |
| 30 | + * req.TransferEncoding = []string{"chunked"} */ |
| 31 | + |
| 32 | + /* then we explicitly read the file... (let's hope it's not stdin) */ |
| 33 | + off, err := GetFileSize(v) |
| 34 | + if err != nil { |
| 35 | + return nil, err |
| 36 | + } |
| 37 | + |
| 38 | + req.ContentLength = off |
| 39 | + vprintln("setting content-length to", off) |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + req.Header.Set("Content-Type", bodyType) |
| 44 | + req.Header.Set("Authorization", fmt.Sprintf("token %s", token)) |
| 45 | + |
| 46 | + return req, nil |
| 47 | +} |
| 48 | + |
| 49 | +func DoAuthRequest(method, url, bodyType, token string, body io.Reader) (*http.Response, error) { |
| 50 | + req, err := NewAuthRequest(method, url, bodyType, token, body) |
| 51 | + if err != nil { |
| 52 | + return nil, err |
| 53 | + } |
| 54 | + |
| 55 | + resp, err := http.DefaultClient.Do(req) |
| 56 | + if err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + |
| 60 | + return resp, nil |
| 61 | +} |
| 62 | + |
| 63 | +func GithubGet(uri string, v interface{}) error { |
| 64 | + resp, err := http.Get(API_URL + uri) |
| 65 | + if err != nil { |
| 66 | + return fmt.Errorf("could not fetch releases, %v", err) |
| 67 | + } |
| 68 | + defer resp.Body.Close() |
| 69 | + |
| 70 | + vprintln("GET", API_URL+uri, "->", resp) |
| 71 | + |
| 72 | + if resp.StatusCode != http.StatusOK { |
| 73 | + return fmt.Errorf("github did not response with 200 OK but with %v", resp.Status) |
| 74 | + } |
| 75 | + |
| 76 | + if VERBOSITY == 0 { |
| 77 | + if err = json.NewDecoder(resp.Body).Decode(v); err != nil { |
| 78 | + return fmt.Errorf("could not unmarshall JSON into Release struct, %v", err) |
| 79 | + } |
| 80 | + } else { |
| 81 | + body, err := ioutil.ReadAll(resp.Body) |
| 82 | + vprintln("BODY", string(body)) |
| 83 | + |
| 84 | + if err = json.Unmarshal(body, v); err != nil { |
| 85 | + return fmt.Errorf("could not unmarshall JSON into Release struct, %v", err) |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + return nil |
| 90 | +} |
0 commit comments