# HTML 资源路径替换功能说明
## 📋 功能概述
在下载网站时,自动将 HTML 文件中的所有资源绝对路径转换为相对路径,使得离线浏览时资源能够正确加载。
---
## ✨ 支持的资源类型
### 1. **CSS 样式表**
```html
```
### 2. **JavaScript 脚本**
```html
```
### 3. **图片资源**
```html
```
### 4. **视频资源**
```html
```
### 5. **音频资源**
```html
```
### 6. **CSS 中的 URL**
```css
/* 替换前 */
background-image: url('https://example.com/images/bg.jpg');
background: url("https://example.com/images/pattern.png");
background: url(https://example.com/images/texture.jpg);
/* 替换后 */
background-image: url('./images/bg.jpg');
background: url("./images/pattern.png");
background: url(./images/texture.jpg);
```
---
## 🔧 技术实现
### 核心函数
#### 1. `replaceHTMLResourcePaths()`
主函数,负责替换 HTML 中的所有资源路径。
```go
func replaceHTMLResourcePaths(htmlContent string, baseURL string) string {
// 解析基础 URL
// 使用正则表达式匹配各种资源标签
// 调用 convertToRelativePath 转换每个 URL
// 返回修改后的 HTML
}
```
#### 2. `convertToRelativePath()`
将绝对 URL 转换为相对路径。
**判断逻辑**:
- ✅ 只替换同域名的资源
- ❌ 跳过外部域名资源
- ❌ 跳过 data:、javascript:、mailto: 等协议
- ❌ 跳过已经是相对路径的资源
```go
func convertToRelativePath(resourceURL, baseURL, baseHost, baseScheme, basePath string) string {
// 1. 验证 URL 类型
// 2. 检查是否同域名
// 3. 计算相对路径
// 4. 返回转换结果
}
```
#### 3. `calculateRelativePath()`
计算两个路径之间的相对路径。
**示例**:
```go
basePath := "/pages/about/"
targetPath := "/css/style.css"
// 结果:../../css/style.css
```
---
## 📊 路径转换示例
### 示例 1:同级目录
```
当前页面:https://example.com/index.html
资源路径:https://example.com/style.css
转换结果:./style.css
```
### 示例 2:子目录
```
当前页面:https://example.com/index.html
资源路径:https://example.com/css/main.css
转换结果:./css/main.css
```
### 示例 3:上级目录
```
当前页面:https://example.com/pages/about.html
资源路径:https://example.com/css/style.css
转换结果:../css/style.css
```
### 示例 4:深层嵌套
```
当前页面:https://example.com/blog/2024/11/post.html
资源路径:https://example.com/images/logo.png
转换结果:../../../images/logo.png
```
### 示例 5:外部资源(不替换)
```
当前页面:https://example.com/index.html
资源路径:https://cdn.example.com/jquery.js
转换结果:https://cdn.example.com/jquery.js(保持不变)
```
---
## 🚫 不会被替换的资源
### 1. **Data URL**
```html
```
### 2. **JavaScript 伪协议**
```html
Click
```
### 3. **锚点链接**
```html
Go to Section 1
```
### 4. **外部域名资源**
```html
```
### 5. **已经是相对路径**
```html
```
---
## 🎯 使用场景
### 1. **离线浏览**
下载整站后,可以在没有网络的情况下正常浏览,所有资源都能正确加载。
### 2. **网站备份**
保存网站的完整副本,包括所有页面和资源,路径关系正确。
### 3. **网站迁移**
将网站从一个域名迁移到另一个域名,资源路径自动适配。
### 4. **本地开发**
在本地环境测试网站,无需配置虚拟主机。
---
## 🔍 处理流程
```
1. 下载 HTML 文件
↓
2. 读取 HTML 内容
↓
3. 解析基础 URL(当前页面地址)
↓
4. 使用正则表达式匹配资源标签
├─
├─