creating a robust http getter (lecture? :))
(ctx context.Context, url string)
| 21 | |
| 22 | // creating a robust http getter (lecture? :)) |
| 23 | func request(ctx context.Context, url string) ([]byte, error) { |
| 24 | req, err := http.NewRequest("GET", url, nil) |
| 25 | if err != nil { |
| 26 | return nil, err |
| 27 | } |
| 28 | |
| 29 | req = req.WithContext(ctx) |
| 30 | |
| 31 | resp, err := http.DefaultClient.Do(req) |
| 32 | if err != nil { |
| 33 | // Get the error from the context. |
| 34 | // It may contain more useful data. |
| 35 | select { |
| 36 | case <-ctx.Done(): |
| 37 | err = ctx.Err() |
| 38 | default: |
| 39 | } |
| 40 | return nil, err |
| 41 | } |
| 42 | defer resp.Body.Close() |
| 43 | |
| 44 | if resp.StatusCode != http.StatusOK { |
| 45 | return nil, fmt.Errorf("Bad Status: %d", resp.StatusCode) |
| 46 | } |
| 47 | |
| 48 | // Prevents the api to shoot us unlimited amount of data |
| 49 | r := io.LimitReader(resp.Body, MaxResponseSize) |
| 50 | |
| 51 | return ioutil.ReadAll(r) |
| 52 | } |
no test coverage detected