65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"m3u8-downloader/pkg/constants"
|
|
"net/http"
|
|
)
|
|
|
|
type Client interface {
|
|
Get(url string) ([]byte, error)
|
|
GetWithContext(ctx context.Context, url string) ([]byte, error)
|
|
}
|
|
|
|
type HTTPWrapper struct {
|
|
client *http.Client
|
|
headers map[string]string
|
|
}
|
|
|
|
func (c *HTTPWrapper) Get(url string) ([]byte, error) {
|
|
return c.GetWithContext(context.Background(), url)
|
|
}
|
|
|
|
func (c *HTTPWrapper) GetWithContext(ctx context.Context, url string) ([]byte, error) {
|
|
if !ValidateURL(url) {
|
|
return nil, errors.New("invalid URL format")
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create request: %w", err)
|
|
}
|
|
|
|
// Set headers
|
|
for key, value := range c.headers {
|
|
req.Header.Set(key, value)
|
|
}
|
|
|
|
resp, err := c.client.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("request failed: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, resp.Status)
|
|
}
|
|
|
|
data, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to read response: %w", err)
|
|
}
|
|
|
|
return data, nil
|
|
}
|
|
|
|
var DefaultClient = &HTTPWrapper{
|
|
client: &http.Client{},
|
|
headers: map[string]string{
|
|
"User-Agent": constants.HTTPUserAgent,
|
|
},
|
|
}
|