FetchFile fetches a single URL into dest. Used for raw repo content (e.g. https://raw.githubusercontent.com/.../README.md).
(url, dest string)
| 159 | // FetchFile fetches a single URL into dest. Used for raw repo content |
| 160 | // (e.g. https://raw.githubusercontent.com/.../README.md). |
| 161 | func (c *Client) FetchFile(url, dest string) error { |
| 162 | req, err := http.NewRequest(http.MethodGet, url, nil) |
| 163 | if err != nil { |
| 164 | return err |
| 165 | } |
| 166 | if c.UserAgent != "" { |
| 167 | req.Header.Set("User-Agent", c.UserAgent) |
| 168 | } |
| 169 | resp, err := c.HTTPClient.Do(req) |
| 170 | if err != nil { |
| 171 | return fmt.Errorf("fetching: get %s: %w", url, err) |
| 172 | } |
| 173 | defer resp.Body.Close() |
| 174 | if resp.StatusCode != http.StatusOK { |
| 175 | return fmt.Errorf("fetching: get %s: HTTP %d", url, resp.StatusCode) |
| 176 | } |
| 177 | if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { |
| 178 | return err |
| 179 | } |
| 180 | out, err := os.Create(dest) |
| 181 | if err != nil { |
| 182 | return err |
| 183 | } |
| 184 | defer out.Close() |
| 185 | if _, err := io.Copy(out, resp.Body); err != nil { |
| 186 | return err |
| 187 | } |
| 188 | return nil |
| 189 | } |