This commit is contained in:
wood chen 2024-09-29 02:13:10 +08:00
parent 85362aad22
commit 08be6ef926
2 changed files with 44 additions and 20 deletions

View File

@ -1,3 +1,8 @@
# 自定义webp-server-go
1. 如果源站没有`etag`, 添加一个默认值, 这是防止很多源站不方便配置;
2. 如果文件非图片类型, 302重定向到源文件
<p align="center"> <p align="center">
<img src="./pics/webp_server.png"/> <img src="./pics/webp_server.png"/>
</p> </p>

View File

@ -61,26 +61,34 @@ func Convert(c *fiber.Ctx) error {
log.Debugf("Incoming connection from %s %s %s", c.IP(), reqHostname, reqURIwithQuery) log.Debugf("Incoming connection from %s %s %s", c.IP(), reqHostname, reqURIwithQuery)
isRedirect := c.Query("webp_redirect") == "true"
if !isRedirect {
if !isImageFile(filename) { if !isImageFile(filename) {
log.Infof("Non-image file requested: %s, redirecting to original URL", filename) log.Infof("Non-image file requested: %s, redirecting to original URL", filename)
var redirectURL string var redirectURL string
if proxyMode {
// 在代理模式下使用原始的远程URL // 检查是否存在匹配的 IMG_MAP
redirectURL = realRemoteAddr for prefix, target := range config.Config.ImageMap {
} else { if strings.HasPrefix(reqURI, prefix) {
// 在非代理模式下构造本地文件的URL // 构造重定向 URL
redirectURL = path.Join(config.Config.ImgPath, reqURI) redirectURL = target + strings.TrimPrefix(reqURI, prefix)
break
}
} }
// 移除查询参数,因为它们可能是用于图像处理的 // 如果没有找到匹配的 IMG_MAP使用默认的处理方式
if redirectURL == "" {
if proxyMode {
redirectURL = realRemoteAddr
} else {
redirectURL = path.Join(config.Config.ImgPath, reqURI)
}
}
// 移除查询参数
redirectURL = strings.Split(redirectURL, "?")[0] redirectURL = strings.Split(redirectURL, "?")[0]
log.Infof("Redirecting to: %s", redirectURL) log.Infof("Redirecting to: %s", redirectURL)
return c.Redirect(redirectURL, 302) return c.Redirect(redirectURL, 302)
} }
}
if !helper.CheckAllowedType(filename) { if !helper.CheckAllowedType(filename) {
@ -214,11 +222,22 @@ func Convert(c *fiber.Ctx) error {
// 新增:检查文件是否为图片的辅助函数 // 新增:检查文件是否为图片的辅助函数
func isImageFile(filename string) bool { func isImageFile(filename string) bool {
ext := strings.ToLower(path.Ext(filename)) ext := strings.ToLower(path.Ext(filename))
allowedExtensions := []string{".jpg",".png",".jpeg",".gif",".bmp",".svg",".heic",".nef",".webp",".tiff"} if ext == "" {
for _, allowedExt := range allowedExtensions {
if ext == allowedExt {
return true
}
}
return false return false
}
ext = ext[1:] // 移除开头的点
// 使用 config.go 中定义的默认 AllowedTypes
defaultImageTypes := config.NewWebPConfig().AllowedTypes
// 检查配置中的 ALLOWED_TYPES
allowedTypes := config.Config.AllowedTypes
// 如果 ALLOWED_TYPES 包含 "*",使用默认列表
if slices.Contains(allowedTypes, "*") {
allowedTypes = defaultImageTypes
}
// 检查文件扩展名是否在允许的类型列表中
return slices.Contains(allowedTypes, ext)
} }