Files
mailx/html.go
T
2026-08-15 01:38:05 +08:00

52 lines
1.3 KiB
Go

package mailx
import (
"bytes"
"fmt"
"github.com/PuerkitoBio/goquery"
)
// ParseHTMLResource 解析 HTML 中引用的静态资源地址(css/js/img/video/audio)。
// 返回资源 URL 列表;忽略空属性与 dns-prefetch 预请求。
func ParseHTMLResource(html string) ([]string, error) {
doc, err := goquery.NewDocumentFromReader(bytes.NewBufferString(html))
if err != nil {
return nil, fmt.Errorf("mailx: parse html: %w", err)
}
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" {
return
}
if href, ok := s.Attr("href"); ok && href != "" {
res = append(res, href)
}
})
collect("script", "src")
collect("img", "src")
collect("img", "data-src")
collect("video", "src")
collect("video", "data-src")
collect("audio", "src")
return res, nil
}
// ParseHtmlResource 是 ParseHTMLResource 的旧名称,保留以兼容历史调用,建议使用新名。
//
// Deprecated: 请使用 ParseHTMLResource。
func ParseHtmlResource(html string) ([]string, error) {
return ParseHTMLResource(html)
}