51 lines
1.0 KiB
Go
51 lines
1.0 KiB
Go
package osimage
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/klauspost/compress/zstd"
|
|
)
|
|
|
|
func OpenDecompressedHTTPStream(ctx context.Context, url string, timeout time.Duration) (io.Reader, func() error, error) {
|
|
if url == "" {
|
|
return nil, nil, fmt.Errorf("url is required")
|
|
}
|
|
if timeout <= 0 {
|
|
timeout = 30 * time.Minute
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("build request: %w", err)
|
|
}
|
|
|
|
client := &http.Client{Timeout: timeout}
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("http get %q: %w", url, err)
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
resp.Body.Close()
|
|
return nil, nil, fmt.Errorf("unexpected status: %s", resp.Status)
|
|
}
|
|
|
|
dec, err := zstd.NewReader(resp.Body)
|
|
if err != nil {
|
|
resp.Body.Close()
|
|
return nil, nil, fmt.Errorf("create zstd decoder: %w", err)
|
|
}
|
|
|
|
closeFn := func() error {
|
|
dec.Close()
|
|
return resp.Body.Close()
|
|
}
|
|
|
|
return dec, closeFn, nil
|
|
}
|