Files
gin-article/router.go
T
2023-03-10 11:52:36 +08:00

52 lines
1.0 KiB
Go

package main
import (
"embed"
"gin-article/handler"
"path/filepath"
"github.com/gin-contrib/multitemplate"
"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 {
r := gin.Default()
r.HTMLRender = loadTemplates("./tmpl")
r.Static("/statics", "statics")
r.GET("/", handler.Index)
r.GET("/article/:id", handler.GetArticle)
return r
}