编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Go Gin框架Web应用embed打包静态文件和模板文件

wxchong 2024-07-25 13:32:23 开源技术 19 ℃ 0 评论
package main

import (
	"embed"
	"github.com/gin-gonic/gin"
	"html/template"
	"io/fs"
	"net/http"
)
//使用go:embed static template定义静态文件目录和模板文件目录
//这里的//go:embed static template并不是注释的意思
//go:embed static template
var f embed.FS

func main() {

	app := gin.Default()
	//设置模板文件目录
	temple := template.Must(template.New("x").ParseFS(f, "template/**/*"))
	app.SetHTMLTemplate(temple)
	//设置静态文件目录
	fp, _ := fs.Sub(f, "static")
	app.StaticFS("/static", http.FS(fp))
	//GET请求,“/”
	app.GET("/", func(c *gin.Context) {
		c.HTML(200, "index/index", nil)
	})
	//GET请求,“/admin”
	app.GET("/admin", func(c *gin.Context) {
		c.HTML(200, "admin/index", nil)
	})
	//运行
	_ = app.Run("127.0.0.1:80")
}

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表