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

51 lines
1.0 KiB
Go

package main
import (
"gin-article/handler"
"os"
"path/filepath"
"github.com/gin-contrib/multitemplate"
"github.com/gin-gonic/gin"
)
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()
themePath := os.Getenv("THEME_PATH")
if len(themePath) == 0 {
themePath = "./theme_example"
}
r.HTMLRender = loadTemplates(themePath + "/tmpl")
r.Static("/statics", themePath+"/statics")
r.GET("/", handler.Index)
r.GET("/article/:id", handler.GetArticle)
return r
}