implemennted downloader

This commit is contained in:
2025-06-23 09:45:42 +03:00
parent 4db033dc7d
commit 610fb3da11
4 changed files with 170 additions and 0 deletions

View 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
}