cdn_handlers.go 2.1 KB

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