cdn_handlers.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package controller
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "os"
  7. "path"
  8. "strings"
  9. "git.aetherial.dev/aeth/keiji/pkg/storage"
  10. "github.com/gin-gonic/gin"
  11. )
  12. // @Name ServeImage
  13. // @Summary serves image from the image store
  14. // @Tags cdn
  15. // @Router /images/{file} [get]
  16. func (c *Controller) ServeImage(ctx *gin.Context) {
  17. f, exist := ctx.Params.Get("file")
  18. if !exist {
  19. ctx.JSON(404, map[string]string{
  20. "Error": "the requested file could not be found",
  21. })
  22. }
  23. css := fmt.Sprintf("%s/%s", storage.GetImageStore(), f)
  24. b, err := os.ReadFile(css)
  25. if err != nil {
  26. ctx.JSON(500, map[string]string{
  27. "Error": "Could not serve the requested file",
  28. "msg": err.Error(),
  29. })
  30. }
  31. ctx.Data(200, "image/jpeg", b)
  32. }
  33. // @Name ServeAsset
  34. // @Summary serves file from the html file
  35. // @Tags cdn
  36. // @Router /api/v1/assets/{file} [get]
  37. func (c *Controller) ServeAsset(ctx *gin.Context) {
  38. f, exist := ctx.Params.Get("file")
  39. if !exist {
  40. ctx.JSON(404, map[string]string{
  41. "Error": "the requested file could not be found",
  42. })
  43. return
  44. }
  45. assets := c.database.GetAssets()
  46. for i := range assets {
  47. if strings.Contains(assets[i].Name, f) {
  48. ctx.Data(200, "image/png", assets[i].Data)
  49. return
  50. }
  51. }
  52. ctx.Data(http.StatusNotFound, "text", []byte("Couldnt find the image requested."))
  53. }
  54. // @Name ServeGeneric
  55. // @Summary serves file from the html file
  56. // @Tags cdn
  57. // @Router /api/v1/cdn/{file} [get]
  58. func (c *Controller) ServeGeneric(ctx *gin.Context) {
  59. f, exist := ctx.Params.Get("file")
  60. if !exist {
  61. ctx.JSON(404, map[string]string{
  62. "Error": "the requested file could not be found",
  63. })
  64. return
  65. }
  66. fext := strings.Split(f, ".")[len(strings.Split(f, "."))-1]
  67. var ctype string
  68. switch {
  69. case fext == "css":
  70. ctype = "text/css"
  71. case fext == "js":
  72. ctype = "text/javascript"
  73. case fext == "json" || fext == "map":
  74. ctype = "application/json"
  75. case fext == "png":
  76. ctype = "image/png"
  77. default:
  78. ctype = "text"
  79. }
  80. fh, err := c.FileIO.Open(path.Join("cdn", f))
  81. if err != nil {
  82. ctx.JSON(500, map[string]string{
  83. "Error": "Could not serve the requested file",
  84. "msg": err.Error(),
  85. })
  86. return
  87. }
  88. b, err := io.ReadAll(fh)
  89. if err != nil {
  90. ctx.JSON(500, map[string]string{
  91. "Error": "Could not serve the requested file",
  92. "msg": err.Error(),
  93. })
  94. return
  95. }
  96. ctx.Data(200, ctype, b)
  97. }