implemennted downloader
This commit is contained in:
64
pkg/downloader/downloader.go
Normal file
64
pkg/downloader/downloader.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package downloader
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// HTTPDownloader реализует интерфейс interfaces.FileDownloader.
|
||||
type HTTPDownloader struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewHTTPDownloader создает новый экземпляр загрузчика.
|
||||
func NewHTTPDownloader() *HTTPDownloader {
|
||||
return &HTTPDownloader{
|
||||
client: &http.Client{},
|
||||
}
|
||||
}
|
||||
|
||||
// Download скачивает файл по URL и сохраняет его во временный файл.
|
||||
// Возвращает путь к скачанному файлу.
|
||||
func (d *HTTPDownloader) Download(ctx context.Context, url string) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create download request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := d.client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to execute download request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("bad status code on download: %s", resp.Status)
|
||||
}
|
||||
|
||||
// Создаем временный файл с правильным расширением
|
||||
tmpFile, err := os.CreateTemp("", "track-*.tmp")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create temp file: %w", err)
|
||||
}
|
||||
defer tmpFile.Close()
|
||||
|
||||
_, err = io.Copy(tmpFile, resp.Body)
|
||||
if err != nil {
|
||||
// Если произошла ошибка, удаляем временный файл
|
||||
os.Remove(tmpFile.Name())
|
||||
return "", fmt.Errorf("failed to write to temp file: %w", err)
|
||||
}
|
||||
|
||||
// Переименовываем файл, чтобы убрать .tmp расширение (не обязательно, но красиво)
|
||||
finalPath := strings.TrimSuffix(tmpFile.Name(), filepath.Ext(tmpFile.Name()))
|
||||
if err := os.Rename(tmpFile.Name(), finalPath); err != nil {
|
||||
return "", fmt.Errorf("failed to rename temp file: %w", err)
|
||||
}
|
||||
|
||||
return finalPath, nil
|
||||
}
|
||||
Reference in New Issue
Block a user