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

52 lines
1.1 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()
themeName := os.Getenv("THEME_NAME")
if len(themeName) == 0 {
themeName = "theme_example"
}
r.HTMLRender = loadTemplates("./theme/" + themeName + "/tmpl")
r.Static("/statics", "./theme/"+themeName+"/statics")
r.StaticFile("/favicon.ico", "./theme/"+themeName+"/favicon.ico")
r.GET("/", handler.Index)
r.GET("/article/:id", handler.GetArticle)
return r
}