移除错误处理模块并更新目标URL获取逻辑,调整返回值以支持备用目标标记。

This commit is contained in:
wood chen 2025-03-22 16:03:51 +08:00
parent 9c2bc25bfa
commit c85d08d7a4
3 changed files with 17 additions and 27 deletions

View File

@ -1,22 +0,0 @@
package errors
type ErrorCode int
const (
ErrInvalidConfig ErrorCode = iota + 1
ErrRateLimit
ErrMetricsCollection
)
type MetricsError struct {
Code ErrorCode
Message string
Err error
}
func (e *MetricsError) Error() string {
if e.Err != nil {
return e.Message + ": " + e.Err.Error()
}
return e.Message
}

View File

@ -195,7 +195,7 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
// 使用统一的路由选择逻辑
targetBase := utils.GetTargetURL(h.client, r, pathConfig, decodedPath)
targetBase, usedAltTarget := utils.GetTargetURL(h.client, r, pathConfig, decodedPath)
// 重新编码路径,保留 '/'
parts := strings.Split(decodedPath, "/")
@ -277,6 +277,12 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Encoding", item.ContentEncoding)
}
w.Header().Set("Proxy-Go-Cache", "HIT")
// 如果使用了扩展名映射的备用目标,添加标记响应头
if usedAltTarget {
w.Header().Set("Proxy-Go-AltTarget", "true")
}
if notModified {
w.WriteHeader(http.StatusNotModified)
return
@ -305,6 +311,11 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
copyHeader(w.Header(), resp.Header)
w.Header().Set("Proxy-Go-Cache", "MISS")
// 如果使用了扩展名映射的备用目标,添加标记响应头
if usedAltTarget {
w.Header().Set("Proxy-Go-AltTarget", "true")
}
// 设置响应状态码
w.WriteHeader(resp.StatusCode)

View File

@ -183,9 +183,10 @@ func GetFileSize(client *http.Client, url string) (int64, error) {
}
// GetTargetURL 根据路径和配置决定目标URL
func GetTargetURL(client *http.Client, r *http.Request, pathConfig config.PathConfig, path string) string {
func GetTargetURL(client *http.Client, r *http.Request, pathConfig config.PathConfig, path string) (string, bool) {
// 默认使用默认目标
targetBase := pathConfig.DefaultTarget
usedAltTarget := false
// 如果配置了扩展名映射
if pathConfig.ExtensionMap != nil {
@ -198,7 +199,7 @@ func GetTargetURL(client *http.Client, r *http.Request, pathConfig config.PathCo
contentLength, err := GetFileSize(client, targetBase+path)
if err != nil {
log.Printf("[Route] %s -> %s (error getting size: %v)", path, targetBase, err)
return targetBase
return targetBase, false
}
// 如果没有设置最小阈值,使用默认值 500KB
@ -244,7 +245,7 @@ func GetTargetURL(client *http.Client, r *http.Request, pathConfig config.PathCo
log.Printf("[Route] %s -> %s (size: %s > %s and <= %s)",
path, altTarget, FormatBytes(contentLength),
FormatBytes(minThreshold), FormatBytes(maxThreshold))
return altTarget
return altTarget, true
}
log.Printf("[Route] %s -> %s (fallback: alternative target not accessible)",
path, targetBase)
@ -269,7 +270,7 @@ func GetTargetURL(client *http.Client, r *http.Request, pathConfig config.PathCo
log.Printf("[Route] %s -> %s (no extension map)", path, targetBase)
}
return targetBase
return targetBase, usedAltTarget
}
// isTargetAccessible 检查目标URL是否可访问