From fef4228f7c721d3e0c60c78264c536f122b0d9e5 Mon Sep 17 00:00:00 2001 From: wood chen Date: Sun, 29 Sep 2024 16:10:22 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BA=86=E9=9D=9E=E5=9B=BE?= =?UTF-8?q?=E7=89=87=E6=96=87=E4=BB=B6=E8=AF=B7=E6=B1=82=E7=9A=84=E5=A4=84?= =?UTF-8?q?=E7=90=86=E9=80=BB=E8=BE=91=EF=BC=8C=E4=BC=98=E5=8C=96=E4=BA=86?= =?UTF-8?q?=E6=9C=AC=E5=9C=B0=E5=92=8C=E8=BF=9C=E7=A8=8B=E8=B5=84=E6=BA=90?= =?UTF-8?q?=E7=9A=84=E5=8C=BA=E5=88=86=E5=92=8C=E9=87=8D=E5=AE=9A=E5=90=91?= =?UTF-8?q?=E6=96=B9=E5=BC=8F=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- handler/router.go | 33 +++++++++++++++++++++------------ helper/helper.go | 9 +++++++++ 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/handler/router.go b/handler/router.go index 387c55b..0b59a51 100644 --- a/handler/router.go +++ b/handler/router.go @@ -70,35 +70,44 @@ func Convert(c *fiber.Ctx) error { // if !isImageFile(filename) { - log.Infof("Non-image file requested: %s, redirecting to original URL", reqURI) + log.Infof("Non-image file requested: %s", reqURI) var redirectURL string // 检查是否存在匹配的 IMG_MAP for prefix, target := range config.Config.ImageMap { if strings.HasPrefix(reqURI, prefix) { - // 构造重定向 URL - redirectURL = target + strings.TrimPrefix(reqURI, prefix) + // 检查目标是否为远程资源 + if strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://") { + // 远程资源,构造重定向 URL + redirectURL = target + strings.TrimPrefix(reqURI, prefix) + } else { + // 本地资源,按原逻辑处理 + return c.SendFile(path.Join(target, strings.TrimPrefix(reqURI, prefix))) + } break } } - // 如果没有找到匹配的 IMG_MAP,使用默认的处理方式 + // 如果没有找到匹配的 IMG_MAP,或者是本地资源,使用默认的处理方式 if redirectURL == "" { if proxyMode { redirectURL = realRemoteAddr } else { - // 使用完整的请求路径,而不是追加到 ImgPath - redirectURL = path.Join("/", reqURI) + // 本地资源,按原逻辑处理 + localPath := path.Join(config.Config.ImgPath, reqURI) + if helper.FileExists(localPath) { + return c.SendFile(localPath) + } else { + return c.SendStatus(fiber.StatusNotFound) + } } } - // 确保重定向 URL 不会导致循环 - if redirectURL == reqURI || redirectURL == path.Join("/", reqURI) { - return c.SendStatus(fiber.StatusNotFound) + // 只有在确定需要重定向时才执行重定向 + if redirectURL != "" { + log.Infof("Redirecting to: %s", redirectURL) + return c.Redirect(redirectURL, fiber.StatusFound) } - - log.Infof("Redirecting to: %s", redirectURL) - return c.Redirect(redirectURL, fiber.StatusFound) } // diff --git a/helper/helper.go b/helper/helper.go index c4237d2..0be4ff1 100644 --- a/helper/helper.go +++ b/helper/helper.go @@ -200,3 +200,12 @@ func HashFile(filepath string) string { buf, _ := os.ReadFile(filepath) return fmt.Sprintf("%x", xxhash.Sum64(buf)) } + +// 检查本地文件 +func FileExists(filename string) bool { + info, err := os.Stat(filename) + if os.IsNotExist(err) { + return false + } + return !info.IsDir() +}