diff --git a/README.md b/README.md index 85b1aa0..a46b6ba 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ The **walrus-go** SDK provides a Go client for interacting with the [Walrus](htt - [Read](#read) - [ReadToFile](#readtofile) - [GetAPISpec](#getapispec) + - [ReadToReader](#readtoreader) - [Contributing](#contributing) - [License](#license) @@ -235,6 +236,39 @@ if err != nil { fmt.Println("File retrieved successfully") ``` +### ReadToReader + +Retrieves a blob and returns an io.ReadCloser for streaming the content. + +```go +func (c *Client) ReadToReader(blobID string) (io.ReadCloser, error) +``` + +**Parameters:** + +- `blobID string`: The blob ID to retrieve. + +**Returns:** + +- `io.ReadCloser`: A reader containing the blob content. Remember to close it after use. +- `error`: Error if the operation fails. + +**Example:** + +```go +reader, err := client.ReadToReader("your-blob-id") +if err != nil { + log.Fatalf("Error getting reader: %v", err) +} +defer reader.Close() + +// Use the reader as needed +_, err = io.Copy(os.Stdout, reader) +if err != nil { + log.Fatalf("Error reading content: %v", err) +} +``` + ## API Reference ### Client @@ -357,6 +391,39 @@ func (c *Client) GetAPISpec(isAggregator bool) ([]byte, error) - `[]byte`: The API specification data. - `error`: Error if the operation fails. +#### ReadToReader + +Retrieves a blob and returns an io.ReadCloser for streaming the content. + +```go +func (c *Client) ReadToReader(blobID string) (io.ReadCloser, error) +``` + +**Parameters:** + +- `blobID string`: The blob ID to retrieve. + +**Returns:** + +- `io.ReadCloser`: A reader containing the blob content. Remember to close it after use. +- `error`: Error if the operation fails. + +**Example:** + +```go +reader, err := client.ReadToReader("your-blob-id") +if err != nil { + log.Fatalf("Error getting reader: %v", err) +} +defer reader.Close() + +// Use the reader as needed +_, err = io.Copy(os.Stdout, reader) +if err != nil { + log.Fatalf("Error reading content: %v", err) +} +``` + ## Contributing Contributions are welcome! Please open an issue or submit a pull request on GitHub. diff --git a/walrus.go b/walrus.go index e4e885a..005a9d9 100644 --- a/walrus.go +++ b/walrus.go @@ -317,3 +317,21 @@ func (c *Client) Head(blobID string) (*BlobMetadata, error) { return metadata, nil } + +// ReadToReader retrieves a blob and writes it to the provided io.Writer +func (c *Client) ReadToReader(blobID string) (io.ReadCloser, error) { + urlStr := fmt.Sprintf("%s/v1/%s", c.AggregatorURL, url.PathEscape(blobID)) + + resp, err := c.httpClient.Get(urlStr) + if err != nil { + return nil, err + } + + if resp.StatusCode != http.StatusOK { + resp.Body.Close() + respData, _ := io.ReadAll(resp.Body) + return nil, fmt.Errorf("failed to read blob: %s", string(respData)) + } + + return resp.Body, nil +}