37 lines
847 B
Go
37 lines
847 B
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
// DownloadObjectToTemp downloads an object into a temporary file and returns
|
|
// the cleaned local path.
|
|
func DownloadObjectToTemp(ctx context.Context, store ObjectStore, key, pattern string) (string, error) {
|
|
if store == nil {
|
|
return "", fmt.Errorf("object store is required")
|
|
}
|
|
if strings.TrimSpace(pattern) == "" {
|
|
return "", fmt.Errorf("temp file pattern is required")
|
|
}
|
|
|
|
tmp, err := os.CreateTemp("", pattern)
|
|
if err != nil {
|
|
return "", fmt.Errorf("create temp file: %w", err)
|
|
}
|
|
path := tmp.Name()
|
|
if err := tmp.Close(); err != nil {
|
|
_ = os.Remove(path)
|
|
return "", fmt.Errorf("close temp file: %w", err)
|
|
}
|
|
|
|
if err := store.Download(ctx, key, path); err != nil {
|
|
_ = os.Remove(path)
|
|
return "", err
|
|
}
|
|
return filepath.Clean(path), nil
|
|
}
|