MCPcopy
hub / github.com/inancgumus/learngo / request

Function request

x-tba/swapi-api-client/request.go:23–52  ·  view source on GitHub ↗

creating a robust http getter (lecture? :))

(ctx context.Context, url string)

Source from the content-addressed store, hash-verified

21
22// creating a robust http getter (lecture? :))
23func 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}

Callers 2

fetchStarshipFunction · 0.85
fetchFilmFunction · 0.85

Calls 1

ErrMethod · 0.65

Tested by

no test coverage detected