1
0

pwa.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package controller
  2. import (
  3. "io/fs"
  4. "net/http"
  5. "github.com/gin-gonic/gin"
  6. )
  7. type pwaAsset struct {
  8. path string
  9. contentType string
  10. }
  11. var pwaAssets = map[string]pwaAsset{
  12. "manifest.webmanifest": {path: "dist/manifest.webmanifest", contentType: "application/manifest+json; charset=utf-8"},
  13. "pwa-register.js": {path: "dist/pwa-register.js", contentType: "application/javascript; charset=utf-8"},
  14. "service-worker.js": {path: "dist/service-worker.js", contentType: "application/javascript; charset=utf-8"},
  15. "icons/3x-ui-16.png": {path: "dist/icons/3x-ui-16.png", contentType: "image/png"},
  16. "icons/3x-ui-24.png": {path: "dist/icons/3x-ui-24.png", contentType: "image/png"},
  17. "icons/3x-ui-32.png": {path: "dist/icons/3x-ui-32.png", contentType: "image/png"},
  18. "icons/3x-ui-64.png": {path: "dist/icons/3x-ui-64.png", contentType: "image/png"},
  19. "icons/3x-ui-192.png": {path: "dist/icons/3x-ui-192.png", contentType: "image/png"},
  20. "icons/3x-ui-512.png": {path: "dist/icons/3x-ui-512.png", contentType: "image/png"},
  21. }
  22. func servePWAAsset(c *gin.Context, assetName string) {
  23. asset, ok := pwaAssets[assetName]
  24. if !ok {
  25. c.AbortWithStatus(http.StatusNotFound)
  26. return
  27. }
  28. body, err := fs.ReadFile(distFS, asset.path)
  29. if err != nil {
  30. c.AbortWithStatus(http.StatusNotFound)
  31. return
  32. }
  33. c.Header("Cache-Control", "no-cache, no-store, must-revalidate")
  34. c.Header("Pragma", "no-cache")
  35. c.Header("Expires", "0")
  36. c.Data(http.StatusOK, asset.contentType, body)
  37. }
  38. func ServePWAManifest(c *gin.Context) {
  39. servePWAAsset(c, "manifest.webmanifest")
  40. }
  41. func ServePWARegister(c *gin.Context) {
  42. servePWAAsset(c, "pwa-register.js")
  43. }
  44. func ServePWAServiceWorker(c *gin.Context) {
  45. servePWAAsset(c, "service-worker.js")
  46. }
  47. func ServePWAIcon(c *gin.Context) {
  48. servePWAAsset(c, "icons/"+c.Param("name"))
  49. }