file.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package utils
  2. import (
  3. "net/http"
  4. "path/filepath"
  5. "strings"
  6. )
  7. type FileLoader struct {
  8. http.Handler
  9. }
  10. func NewFileLoader() *FileLoader {
  11. return &FileLoader{}
  12. }
  13. func (f *FileLoader) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  14. if isImageRequest(r.URL.Path) {
  15. // 从URL参数获取图片路径
  16. imagePath := r.URL.Query().Get("path")
  17. if imagePath != "" {
  18. // 安全检查:防止路径遍历攻击
  19. //if IsValidImagePath(imagePath) {
  20. // http.ServeFile(w, r, imagePath)
  21. // return
  22. //}
  23. }
  24. }
  25. // 默认处理其他请求
  26. http.NotFound(w, r)
  27. }
  28. // 检查是否是图片请求
  29. func isImageRequest(path string) bool {
  30. ext := strings.ToLower(filepath.Ext(path))
  31. return ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".webp"
  32. }
  33. // IsValidImagePath 验证图片路径是否安全
  34. func IsValidImagePath(imagePath string) bool {
  35. // 清理路径
  36. cleanPath := filepath.Clean(imagePath)
  37. absPath, err := filepath.Abs(cleanPath)
  38. if err != nil {
  39. return false
  40. }
  41. // 限制在允许的目录范围内,这里可以根据你的项目结构调整
  42. // 例如,只允许访问项目目录下的特定文件夹
  43. allowedDir := "/path/to/your/images/directory" // 替换为实际的允许目录
  44. // 你也可以使用相对路径,如项目根目录下的 images 文件夹
  45. projectRoot, _ := filepath.Abs(".")
  46. allowedDir = filepath.Join(projectRoot, "images")
  47. relPath, err := filepath.Rel(allowedDir, absPath)
  48. if err != nil {
  49. return false
  50. }
  51. return !strings.HasPrefix(relPath, "..")
  52. }