gofiber: 把模板文件打包编译到二进制文件中

一,现象:

$ ./industry 
2024/11/21 10:32:19.288954 app.go:999: [Warn] failed to load views: lstat ./views: no such file or directory

二进制文件启动时会报错找不到views目录

官网文档地址:

https://docs.gofiber.io/template/html/

 

二,解决:

1,main.go

package main

import (
	"embed"
	"github.com/gofiber/template/html/v2"
	"net/http"
	"fmt"
	"industry/config"
	"industry/routes"
)

//go:embed views/*
var viewsfs embed.FS

func init() {
	err := config.SetupDBLink()
	if err != nil {
		fmt.Println("db link error")
	}
}
func main() {

	engine := html.NewFileSystem(http.FS(viewsfs), ".html")
	// 设置路由
	app := routes.SetupRoutes(engine)

	// 启动服务器
	err := app.Listen(":3000")
	if err != nil {
		return
	}
}

2,routes.go

func SetupRoutes(viewEngine *html.Engine) *fiber.App {

    // 创建 Fiber 应用
    app := fiber.New(fiber.Config{
        Views: viewEngine,
    })
    app.Use(recover.New())
    
    ...

3,controller

func (dc *ArticleController) ListArticle(c *fiber.Ctx) error {
    myMap:=fiber.Map{}
	myMap["Title"] = "书店新上图书列表"
	return c.Render("views/article/list", myMap)
}

4,模板

{{template "views/partials/header" .}}

<h1>{{.Title}}</h1>

{{template "views/partials/footer" .}}

 

posted @ 2024-11-23 09:05  刘宏缔的架构森林  阅读(15)  评论(0编辑  收藏  举报