in internal/httprange/resource.go [71:128]
func NewResource(ctx context.Context, url string, httpClient *http.Client) (*Resource, error) {
// the `h.URL` is likely pre-signed URL or a file:// scheme that only supports GET requests
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
// we fetch a single byte and ensure that range requests is additionally supported
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", 0, 0))
// body will be closed by discardAndClose
res, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() {
io.CopyN(io.Discard, res.Body, 1) // since we want to read a single byte
res.Body.Close()
}()
resource := &Resource{
ETag: res.Header.Get("ETag"),
LastModified: res.Header.Get("Last-Modified"),
httpClient: httpClient,
}
resource.SetURL(url)
switch res.StatusCode {
case http.StatusOK:
resource.Size = res.ContentLength
return resource, nil
case http.StatusPartialContent:
contentRange := res.Header.Get("Content-Range")
ranges := strings.SplitN(contentRange, "/", 2)
if len(ranges) != 2 {
return nil, fmt.Errorf("invalid `Content-Range`: %q", contentRange)
}
resource.Size, err = strconv.ParseInt(ranges[1], 0, 64)
if err != nil {
return nil, fmt.Errorf("invalid `Content-Range`: %q %w", contentRange, err)
}
return resource, nil
case http.StatusRequestedRangeNotSatisfiable:
return nil, ErrRangeRequestsNotSupported
case http.StatusNotFound:
return nil, ErrNotFound
default:
return nil, fmt.Errorf("httprange: new resource %d: %q", res.StatusCode, res.Status)
}
}