add proxy option

This commit is contained in:
2025-04-27 12:16:29 +08:00
parent 4cc6941d95
commit e8316b1d1c
3 changed files with 27 additions and 7 deletions

View File

@@ -25,7 +25,7 @@ func main() {
fmt.Printf("name: %s, feedUrl: %s\n", item.CollectionName, item.FeedURL)
feedUrl := "http://www.ximalaya.com/album/19206382.xml"
pod, err := model.LoadFeed(feedUrl, 5*time.Second)
pod, err := model.LoadFeed(feedUrl, "", 5*time.Second)
if err != nil {
panic(err)
}

View File

@@ -4,9 +4,12 @@ package model
import (
"context"
"fmt"
"net/http"
"net/url"
"time"
"github.com/mmcdole/gofeed"
"github.com/sirupsen/logrus"
)
// Podcast 表示一个播客及其剧集
@@ -61,7 +64,7 @@ type Podcast struct {
}
// LoadFeed 从URL加载播客RSS订阅timeout为超时时间如果timeout<=0则使用默认值30秒
func LoadFeed(url string, timeout time.Duration) (*Podcast, error) {
func LoadFeed(feedURL, proxy string, timeout time.Duration) (*Podcast, error) {
if timeout <= 0 {
timeout = 30 * time.Second
}
@@ -70,7 +73,24 @@ func LoadFeed(url string, timeout time.Duration) (*Podcast, error) {
defer cancel()
fp := gofeed.NewParser()
feed, err := fp.ParseURLWithContext(url, ctx)
fp.Client = &http.Client{}
// setup proxy
if proxy != "" {
proxyURL, err := url.Parse(proxy)
if err != nil {
logrus.WithError(err).Errorf("Failed to parse proxy url: %s", proxy)
return nil, err
}
fp.Client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyURL(proxyURL),
},
}
logrus.Infof("Using proxy: %s", proxy)
}
feed, err := fp.ParseURLWithContext(feedURL, ctx)
if err != nil {
return nil, fmt.Errorf("解析播客订阅失败: %w", err)
}

View File

@@ -38,7 +38,7 @@ func TestLoadFeed_Success(t *testing.T) {
defer server.Close()
// Call LoadFeed
podcast, err := LoadFeed(server.URL, 10*time.Second)
podcast, err := LoadFeed(server.URL, "", 10*time.Second)
// Assertions
assert.NoError(t, err)
@@ -62,7 +62,7 @@ func TestLoadFeed_Timeout(t *testing.T) {
defer server.Close()
// Call LoadFeed with a short timeout
_, err := LoadFeed(server.URL, 1*time.Second)
_, err := LoadFeed(server.URL, "", 1*time.Second)
// Assertions
assert.Error(t, err)
@@ -71,7 +71,7 @@ func TestLoadFeed_Timeout(t *testing.T) {
func TestLoadFeed_InvalidURL(t *testing.T) {
// Call LoadFeed with an invalid URL
_, err := LoadFeed("http://invalid-url", 10*time.Second)
_, err := LoadFeed("http://invalid-url", "", 10*time.Second)
// Assertions
assert.Error(t, err)
@@ -86,7 +86,7 @@ func TestLoadFeed_EmptyFeed(t *testing.T) {
defer server.Close()
// Call LoadFeed
_, err := LoadFeed(server.URL, 10*time.Second)
_, err := LoadFeed(server.URL, "", 10*time.Second)
// Assertions
assert.Error(t, err)