package web import ( "embed" "io/fs" "net/http" "github.com/gin-gonic/gin" "github.com/infraboard/mcube/v2/ioc" ioc_gin "github.com/infraboard/mcube/v2/ioc/config/gin" ) func init() { ioc.Config().Registry(&Web{}) } // 把当前的dist文件 作为静态资源 加载到Gin type Web struct { ioc.ObjectImpl } func (w *Web) Name() string { return "web" } //go:embed dist/assets/* var assetsFs embed.FS //go:embed dist/index.html var indexFs embed.FS func (w Web) Init() error { rr := ioc_gin.RootRouter() // dist/assets/xxx/xxx --> /assets/xxx/xxx assets, _ := fs.Sub(assetsFs, "dist/assets") // /assets/xx.jpg --> dist/assets(root), xx.jpg rr.StaticFS("/assets", http.FS(assets)) // index页面 rr.GET("", w.Index) // 解决刷新404问题, 解决不了刷新 URL重置问题 rr.NoRoute(w.RedirectIndex) return nil } // RedirectIndex 重定向 // // location / { // try_files $uri $uri/ /index.html; // } func (h *Web) RedirectIndex(c *gin.Context) { c.Redirect(http.StatusFound, "/") } // RedirectIndex 重定向 func (h *Web) Index(c *gin.Context) { c.Header("Content-Type", "text/html;charset=utf-8") index, err := indexFs.ReadFile("dist/index.html") if err != nil { panic(err) } c.String(200, string(index)) }