Files
mailx/html.go
T

52 lines
1.3 KiB
Go
Raw Normal View History

2024-08-23 15:09:37 +08:00
package mailx
import (
"bytes"
2026-08-15 01:38:05 +08:00
"fmt"
2024-08-23 15:09:37 +08:00
"github.com/PuerkitoBio/goquery"
)
2026-08-15 01:38:05 +08:00
// ParseHTMLResource 解析 HTML 中引用的静态资源地址(css/js/img/video/audio)。
// 返回资源 URL 列表;忽略空属性与 dns-prefetch 预请求。
func ParseHTMLResource(html string) ([]string, error) {
doc, err := goquery.NewDocumentFromReader(bytes.NewBufferString(html))
2024-08-23 15:09:37 +08:00
if err != nil {
2026-08-15 01:38:05 +08:00
return nil, fmt.Errorf("mailx: parse html: %w", err)
2024-08-23 15:09:37 +08:00
}
2026-08-15 01:38:05 +08:00
var res []string
collect := func(sel, attr string) {
doc.Find(sel).Each(func(_ int, s *goquery.Selection) {
if v, ok := s.Attr(attr); ok && v != "" {
res = append(res, v)
}
})
}
// link:跳过 dns-prefetch
doc.Find("link").Each(func(_ int, s *goquery.Selection) {
if rel, ok := s.Attr("rel"); ok && rel == "dns-prefetch" {
2024-08-23 15:09:37 +08:00
return
}
2026-08-15 01:38:05 +08:00
if href, ok := s.Attr("href"); ok && href != "" {
res = append(res, href)
2024-08-23 15:09:37 +08:00
}
})
2026-08-15 01:38:05 +08:00
collect("script", "src")
collect("img", "src")
collect("img", "data-src")
collect("video", "src")
collect("video", "data-src")
collect("audio", "src")
2024-08-23 15:09:37 +08:00
2026-08-15 01:38:05 +08:00
return res, nil
}
// ParseHtmlResource 是 ParseHTMLResource 的旧名称,保留以兼容历史调用,建议使用新名。
//
// Deprecated: 请使用 ParseHTMLResource。
func ParseHtmlResource(html string) ([]string, error) {
return ParseHTMLResource(html)
2024-08-23 15:09:37 +08:00
}