package utils import ( "net/http" "path/filepath" "strings" ) type FileLoader struct { http.Handler } func NewFileLoader() *FileLoader { return &FileLoader{} } func (f *FileLoader) ServeHTTP(w http.ResponseWriter, r *http.Request) { if isImageRequest(r.URL.Path) { // 从URL参数获取图片路径 imagePath := r.URL.Query().Get("path") if imagePath != "" { // 安全检查:防止路径遍历攻击 //if IsValidImagePath(imagePath) { // http.ServeFile(w, r, imagePath) // return //} } } // 默认处理其他请求 http.NotFound(w, r) } // 检查是否是图片请求 func isImageRequest(path string) bool { ext := strings.ToLower(filepath.Ext(path)) return ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".webp" } // IsValidImagePath 验证图片路径是否安全 func IsValidImagePath(imagePath string) bool { // 清理路径 cleanPath := filepath.Clean(imagePath) absPath, err := filepath.Abs(cleanPath) if err != nil { return false } // 限制在允许的目录范围内,这里可以根据你的项目结构调整 // 例如,只允许访问项目目录下的特定文件夹 allowedDir := "/path/to/your/images/directory" // 替换为实际的允许目录 // 你也可以使用相对路径,如项目根目录下的 images 文件夹 projectRoot, _ := filepath.Abs(".") allowedDir = filepath.Join(projectRoot, "images") relPath, err := filepath.Rel(allowedDir, absPath) if err != nil { return false } return !strings.HasPrefix(relPath, "..") }