(ctx context.Context, url string, limit int64)
| 99 | } |
| 100 | |
| 101 | func (s *Server) fetchTutorialBytes(ctx context.Context, url string, limit int64) ([]byte, string, error) { |
| 102 | ctx, cancel := context.WithTimeout(ctx, tutorialsFetchTimeout) |
| 103 | defer cancel() |
| 104 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 105 | if err != nil { |
| 106 | return nil, "", err |
| 107 | } |
| 108 | // Never follow a redirect: the origin check is on the URL asked for, and a |
| 109 | // redirect would let an allowed getpad.dev URL send this server anywhere. |
| 110 | // A 3xx is then just a non-200, and the fetch fails. |
| 111 | client := *s.tutorialsClient() |
| 112 | client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| 113 | resp, err := client.Do(req) |
| 114 | if err != nil { |
| 115 | return nil, "", err |
| 116 | } |
| 117 | defer resp.Body.Close() |
| 118 | if resp.StatusCode != http.StatusOK { |
| 119 | return nil, "", fmt.Errorf("tutorials: %s answered %d", url, resp.StatusCode) |
| 120 | } |
| 121 | body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) |
| 122 | if err != nil { |
| 123 | return nil, "", err |
| 124 | } |
| 125 | if int64(len(body)) > limit { |
| 126 | return nil, "", fmt.Errorf("tutorials: %s is larger than %d bytes", url, limit) |
| 127 | } |
| 128 | return body, resp.Header.Get("Content-Type"), nil |
| 129 | } |
| 130 | |
| 131 | // tutorialCatalogNow returns the catalog, refreshing it when it is older than |
| 132 | // the TTL. One refresh runs at a time and never holds the lock while it waits |
no test coverage detected