Skip to content

Commit 08c3a52

Browse files
committed
fix: 修复下载链接重定向后无法查找到有效类型的问题
1 parent ba398ca commit 08c3a52

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,6 @@ logs/
4848

4949
.docs
5050
.claude
51-
CLAUDE.md
51+
CLAUDE.md
52+
53+
mynest

backend/service/download_service.go

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -438,14 +438,40 @@ func (s *DownloadService) extractFilenameFromURL(urlStr string) string {
438438
}
439439

440440
func (s *DownloadService) detectFilenameByContentType(ctx context.Context, urlStr string) string {
441-
// 发送 HEAD 请求获取 Content-Type
442-
resp, err := http.Head(urlStr)
441+
// 创建支持重定向的 HTTP 客户端(使用默认 Transport 以支持代理)
442+
client := &http.Client{
443+
Timeout: 10 * time.Second,
444+
Transport: http.DefaultTransport, // 自动从环境变量读取 HTTP_PROXY/HTTPS_PROXY
445+
CheckRedirect: func(req *http.Request, via []*http.Request) error {
446+
// 最多跟随 10 次重定向
447+
if len(via) >= 10 {
448+
return fmt.Errorf("stopped after 10 redirects")
449+
}
450+
return nil
451+
},
452+
}
453+
454+
// 发送 HEAD 请求获取 Content-Type(跟随重定向)
455+
req, err := http.NewRequestWithContext(ctx, http.MethodHead, urlStr, nil)
456+
if err != nil {
457+
log.Printf("[Download] Failed to create HEAD request: %v", err)
458+
return ""
459+
}
460+
461+
// 添加常见的请求头,避免某些服务器拒绝 HEAD 请求
462+
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
463+
req.Header.Set("Accept", "*/*")
464+
465+
resp, err := client.Do(req)
443466
if err != nil {
444467
log.Printf("[Download] Failed to HEAD request: %v", err)
445468
return ""
446469
}
447470
defer resp.Body.Close()
448471

472+
log.Printf("[Download] HEAD request for %s: status=%d, content-type=%s, final-url=%s",
473+
urlStr, resp.StatusCode, resp.Header.Get("Content-Type"), resp.Request.URL.String())
474+
449475
// 从 Content-Type 获取扩展名
450476
contentType := resp.Header.Get("Content-Type")
451477
if contentType != "" {

0 commit comments

Comments
 (0)