-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: collect shared logic for blob storage and minio
- Loading branch information
1 parent
3b853d0
commit ad59e80
Showing
3 changed files
with
110 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package blobstorage | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
|
||
"google.golang.org/grpc/metadata" | ||
) | ||
|
||
func UploadFile(ctx context.Context, uploadURL string, data []byte, contentType string) error { | ||
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, uploadURL, nil) | ||
|
||
if err != nil { | ||
return fmt.Errorf("creating request: %w", err) | ||
} | ||
|
||
body := bytes.NewReader(data) | ||
contentLength := int64(len(data)) | ||
req.Body = io.NopCloser(body) | ||
req.Header = metadataToHTTPHeaders(ctx) | ||
|
||
req.ContentLength = contentLength | ||
req.Header.Set("Content-Type", contentType) | ||
req.Header.Del("Authorization") | ||
|
||
client := &http.Client{} | ||
resp, err := client.Do(req) | ||
|
||
if err != nil { | ||
return fmt.Errorf("uploading blob: %w", err) | ||
} | ||
defer resp.Body.Close() | ||
|
||
if resp.StatusCode != http.StatusOK { | ||
body, _ := io.ReadAll(resp.Body) | ||
return fmt.Errorf("upload failed with status %d: %s", resp.StatusCode, string(body)) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func metadataToHTTPHeaders(ctx context.Context) http.Header { | ||
headers := http.Header{} | ||
md, ok := metadata.FromOutgoingContext(ctx) | ||
if !ok { | ||
return headers | ||
} | ||
for key, values := range md { | ||
for _, value := range values { | ||
headers.Add(key, value) | ||
} | ||
} | ||
return headers | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
// TODO: add test for blobstorage | ||
package blobstorage |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters