57 lines
1.6 KiB
Go
57 lines
1.6 KiB
Go
package downloader
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"os"
|
||
)
|
||
|
||
// 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)
|
||
}
|
||
|
||
// Создаем временный файл с правильным расширением .mp3
|
||
tmpFile, err := os.CreateTemp("", "track-*.mp3")
|
||
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)
|
||
}
|
||
|
||
return tmpFile.Name(), nil
|
||
}
|