view_view_file.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package route
  2. import (
  3. "net/http"
  4. "os"
  5. "path"
  6. "path/filepath"
  7. "regexp"
  8. "strings"
  9. "github.com/gin-gonic/gin"
  10. )
  11. func View_view_file(c *gin.Context) {
  12. raw_path := strings.TrimPrefix(c.Param("name"), "/")
  13. if raw_path == "" {
  14. c.String(http.StatusOK, "")
  15. return
  16. }
  17. dir_name := path.Dir(raw_path)
  18. file_name := path.Base(raw_path)
  19. if file_name == "." || file_name == "/" {
  20. c.String(http.StatusOK, "")
  21. return
  22. }
  23. re_cache := regexp.MustCompile(`\.cache_v[0-9]+$`)
  24. file_name = re_cache.ReplaceAllString(file_name, "")
  25. re_dots := regexp.MustCompile(`\.{2,}`)
  26. dir_name = re_dots.ReplaceAllString(dir_name, "")
  27. dir_name = filepath.ToSlash(filepath.Clean(dir_name))
  28. if strings.HasPrefix(dir_name, "../") || strings.Contains(dir_name, "/../") {
  29. c.String(http.StatusBadRequest, "bad path")
  30. return
  31. }
  32. parts := strings.Split(file_name, ".")
  33. mime_type := "text/plain"
  34. if len(parts) >= 2 {
  35. ext := strings.ToLower(parts[len(parts) - 1])
  36. switch ext {
  37. case "jpeg", "jpg", "gif", "png", "webp", "ico":
  38. mime_type = "image/" + ext
  39. case "svg":
  40. mime_type = "image/svg+xml"
  41. case "js":
  42. mime_type = "text/javascript"
  43. case "txt":
  44. mime_type = "text/plain"
  45. default:
  46. mime_type = "text/" + ext
  47. }
  48. }
  49. final_path := filepath.Join("..", "views", dir_name, file_name)
  50. if _, err := os.Stat(final_path); err != nil {
  51. if os.IsNotExist(err) {
  52. c.String(http.StatusOK, "")
  53. return
  54. }
  55. c.String(http.StatusInternalServerError, "read error")
  56. return
  57. }
  58. if strings.HasPrefix(mime_type, "image/") && mime_type != "image/svg+xml" {
  59. c.Header("Content-Type", mime_type)
  60. } else {
  61. c.Header("Content-Type", mime_type+"; charset=utf-8")
  62. }
  63. c.File(final_path)
  64. }