Files
yamusic-bot/pkg/downloader/downloader.go
Vladimir Zagainov 587676be58
Some checks failed
continuous-integration/drone/push Build is failing
MVP done
2025-06-23 13:02:10 +03:00

57 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
}