github.com/soulteary/pocket-bookcase@v0.0.0-20240428065142-0b5a9a0fc98a/internal/http/routes/frontend.go (about) 1 package routes 2 3 import ( 4 "embed" 5 "net/http" 6 "path" 7 8 "github.com/gin-contrib/static" 9 "github.com/gin-gonic/gin" 10 "github.com/sirupsen/logrus" 11 "github.com/soulteary/pocket-bookcase/internal/config" 12 "github.com/soulteary/pocket-bookcase/internal/model" 13 views "github.com/soulteary/pocket-bookcase/internal/view" 14 ) 15 16 type assetsFS struct { 17 http.FileSystem 18 logger *logrus.Logger 19 } 20 21 func (fs assetsFS) Exists(prefix string, path string) bool { 22 _, err := fs.Open(path) 23 if err != nil { 24 logrus.WithError(err).WithField("path", path).WithField("prefix", prefix).Error("requested frontend file not found") 25 } 26 return err == nil 27 } 28 29 func (fs assetsFS) Open(name string) (http.File, error) { 30 f, err := fs.FileSystem.Open(path.Join("assets", name)) 31 if err != nil { 32 logrus.WithError(err).WithField("path", name).Error("requested frontend file not found") 33 } 34 return f, err 35 } 36 37 func newAssetsFS(logger *logrus.Logger, fs embed.FS) static.ServeFileSystem { 38 return assetsFS{ 39 logger: logger, 40 FileSystem: http.FS(fs), 41 } 42 } 43 44 type FrontendRoutes struct { 45 logger *logrus.Logger 46 cfg *config.Config 47 } 48 49 func (r *FrontendRoutes) Setup(e *gin.Engine) { 50 group := e.Group("/") 51 group.GET("/login", func(ctx *gin.Context) { 52 ctx.HTML(http.StatusOK, "login.html", gin.H{ 53 "RootPath": r.cfg.Http.RootPath, 54 "Version": model.BuildVersion, 55 }) 56 }) 57 group.GET("/", func(ctx *gin.Context) { 58 ctx.HTML(http.StatusOK, "index.html", gin.H{ 59 "RootPath": r.cfg.Http.RootPath, 60 "Version": model.BuildVersion, 61 }) 62 }) 63 e.StaticFS("/assets", newAssetsFS(r.logger, views.Assets)) 64 } 65 66 func NewFrontendRoutes(logger *logrus.Logger, cfg *config.Config) *FrontendRoutes { 67 return &FrontendRoutes{ 68 logger: logger, 69 cfg: cfg, 70 } 71 }