go17/vblog/web/web.go

57 lines
1.1 KiB
Go
Raw Permalink Normal View History

2025-01-19 18:16:29 +08:00
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"
}
2025-02-16 09:11:16 +08:00
//go:embed dist/*
var WebDir embed.FS
2025-01-19 18:16:29 +08:00
func (w Web) Init() error {
rr := ioc_gin.RootRouter()
2025-02-16 09:11:16 +08:00
// 嵌入的 embed 就是一个文件系统,获取 web 目录下的资源文件
staticFp, err := fs.Sub(WebDir, "dist")
2025-01-19 18:16:29 +08:00
if err != nil {
2025-02-16 09:11:16 +08:00
return err
2025-01-19 18:16:29 +08:00
}
2025-02-16 09:11:16 +08:00
// 所有请求先匹配 api 路由,如果没匹配到就当作静态资源文件处理
rr.NoRoute(gin.WrapH(http.FileServer(http.FS(staticFp))))
return nil
2025-01-19 18:16:29 +08:00
}
2025-02-16 09:11:16 +08:00
// // RedirectIndex 重定向
// 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))
// }