Update frontend handler to serve static files from embedded FS for selfhosted option

This commit is contained in:
Mo Tarbin 2024-07-24 23:55:23 -04:00
parent 670ac84009
commit 71f8dfb26c
2 changed files with 34 additions and 8 deletions

9
frontend/dist/index.html vendored Normal file
View File

@ -0,0 +1,9 @@
<html>
<head>
<title>This file will be replaced by the frontend build process</title>
</head>
<body>
<h5>This file will be replaced by the frontend build process</h5>
</body>
</html>

View File

@ -23,15 +23,15 @@ func NewHandler(config *config.Config) *Handler {
} }
func Routes(router *gin.Engine, h *Handler) { func Routes(router *gin.Engine, h *Handler) {
if h.ServeFrontend { // this whole logic is walkaround for serving frontend files
router.Use(staticMiddleware("dist")) // TODO: figure out better way to improve it. main issue i run into is failing over to index.html when file does not exist
router.Static("/assets", "dist/assets")
if h.ServeFrontend {
// if file exists in dist folder, serve it
router.Use(staticMiddleware("dist"))
// if file does not exist in dist folder fallback to index.html
router.NoRoute(staticMiddlewareNoRoute("dist"))
// Gzip compression middleware
router.Group("/assets").Use(func(c *gin.Context) {
c.Header("Cache-Control", "max-age=31536000, immutable")
c.Next()
})
} }
} }
@ -40,7 +40,24 @@ func staticMiddleware(root string) gin.HandlerFunc {
fileServer := http.FileServer(getFileSystem(root)) fileServer := http.FileServer(getFileSystem(root))
return func(c *gin.Context) { return func(c *gin.Context) {
_, err := fs.Stat(embeddedFiles, "dist"+c.Request.URL.Path)
if err != nil {
c.Next()
return
}
fileServer.ServeHTTP(c.Writer, c.Request) fileServer.ServeHTTP(c.Writer, c.Request)
}
}
func staticMiddlewareNoRoute(root string) gin.HandlerFunc {
fileServer := http.FileServer(getFileSystem(root))
// always serve index.html for any route does not match:
return func(c *gin.Context) {
// Rewrite all requests to serve index.html
c.Request.URL.Path = "/"
fileServer.ServeHTTP(c.Writer, c.Request)
} }
} }