This commit is contained in:
2023-03-10 11:11:43 +08:00
parent c833d1864e
commit 96338dd73e
+37
View File
@@ -1,14 +1,51 @@
package main package main
import ( import (
"embed"
"fmt"
"gin-article/handler" "gin-article/handler"
"path/filepath"
"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
//go:embed tmpl/*
var tmplFs embed.FS
//go:embed statics/**/*
var staticsFs embed.FS
func loadTemplates(templatesDir string) multitemplate.Renderer {
r := multitemplate.NewRenderer()
layouts, err := filepath.Glob(templatesDir + "/layouts/*.html")
if err != nil {
panic(err.Error())
}
includes, err := filepath.Glob(templatesDir + "/*.html")
if err != nil {
panic(err.Error())
}
// Generate our templates map from our layouts/ and includes/ directories
for _, include := range includes {
layoutCopy := make([]string, len(layouts))
copy(layoutCopy, layouts)
files := append(layoutCopy, include)
r.AddFromFiles(filepath.Base(include), files...)
}
return r
}
func Router() *gin.Engine { func Router() *gin.Engine {
r := gin.Default() r := gin.Default()
r.HTMLRender = loadTemplates("./tmpl")
fmt.Println(r.HTMLRender)
r.Static("/statics", "statics")
r.GET("/", handler.Index) r.GET("/", handler.Index)
r.GET("/article/:id", handler.GetArticle) r.GET("/article/:id", handler.GetArticle)