Files
mstore/pkg/filecli/getfile.go
T
2026-03-11 19:47:40 +02:00

67 lines
1.5 KiB
Go

/*
* Copyright 2026 Oleg Borodin <onborodin@gmail.com>
*
* This work is published and licensed under a Creative Commons
* Attribution-NonCommercial-NoDerivatives 4.0 International License.
*
* Distribution of this work is permitted, but commercial use and
* modifications are strictly prohibited.
*/
package filecli
import (
"context"
"fmt"
"io"
"net/http"
"strconv"
)
func (cli *Client) GetFile(ctx context.Context, rawpath string, writer io.Writer) (bool, error) {
var err error
var exist bool
ref, err := ParsePath(rawpath)
if err != nil {
return exist, err
}
uri := ref.FileEP()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return exist, err
}
req.Header.Set("User-Agent", cli.userAgent)
req.Header.Set("Accept", "*/*")
resp, err := cli.httpClient.Do(req)
if err != nil {
return exist, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return exist, err
}
if resp.StatusCode != http.StatusOK {
err := fmt.Errorf("Unexpected response code %s", resp.Status)
return exist, err
}
contentLength := resp.Header.Get("Content-Length")
if contentLength == "" {
err := fmt.Errorf("Content-Length header is missing")
return exist, err
}
blobSize, err := strconv.ParseInt(contentLength, 10, 64)
if err != nil {
return exist, err
}
recSize, err := Copy(ctx, writer, resp.Body)
if blobSize != recSize {
err := fmt.Errorf("Mismatch declared and actual body size: %d and %d", blobSize, recSize)
return exist, err
}
exist = true
return exist, err
}