2024-07-24 05:41:08 +01:00
|
|
|
package frontend
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
|
|
|
"io/fs"
|
|
|
|
"net/http"
|
|
|
|
|
2024-07-24 06:07:11 +01:00
|
|
|
"donetick.com/core/config"
|
2024-07-24 05:41:08 +01:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
|
|
|
//go:embed dist
|
|
|
|
var embeddedFiles embed.FS
|
|
|
|
|
|
|
|
type Handler struct {
|
2024-07-24 06:07:11 +01:00
|
|
|
ServeFrontend bool
|
2024-07-24 05:41:08 +01:00
|
|
|
}
|
|
|
|
|
2024-07-24 06:07:11 +01:00
|
|
|
func NewHandler(config *config.Config) *Handler {
|
|
|
|
return &Handler{
|
|
|
|
ServeFrontend: config.Server.ServeFrontend,
|
|
|
|
}
|
2024-07-24 05:41:08 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func Routes(router *gin.Engine, h *Handler) {
|
2024-07-25 04:55:23 +01:00
|
|
|
// this whole logic is walkaround for serving frontend files
|
|
|
|
// TODO: figure out better way to improve it. main issue i run into is failing over to index.html when file does not exist
|
|
|
|
|
2024-07-24 06:07:11 +01:00
|
|
|
if h.ServeFrontend {
|
2024-07-25 04:55:23 +01:00
|
|
|
// if file exists in dist folder, serve it
|
2024-07-24 06:07:11 +01:00
|
|
|
router.Use(staticMiddleware("dist"))
|
2024-07-25 04:55:23 +01:00
|
|
|
// if file does not exist in dist folder fallback to index.html
|
|
|
|
router.NoRoute(staticMiddlewareNoRoute("dist"))
|
2024-07-24 06:07:11 +01:00
|
|
|
|
|
|
|
}
|
2024-07-24 05:41:08 +01:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func staticMiddleware(root string) gin.HandlerFunc {
|
|
|
|
fileServer := http.FileServer(getFileSystem(root))
|
|
|
|
|
|
|
|
return func(c *gin.Context) {
|
2024-07-25 04:55:23 +01:00
|
|
|
_, err := fs.Stat(embeddedFiles, "dist"+c.Request.URL.Path)
|
|
|
|
if err != nil {
|
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
2024-07-24 05:41:08 +01:00
|
|
|
fileServer.ServeHTTP(c.Writer, c.Request)
|
2024-07-25 04:55:23 +01:00
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
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)
|
|
|
|
|
2024-07-24 05:41:08 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func getFileSystem(path string) http.FileSystem {
|
|
|
|
fs, err := fs.Sub(embeddedFiles, path)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return http.FS(fs)
|
|
|
|
}
|