Golang Embed native instructions embed project static files into binary

Embed directive

  • //go:embedDirectives support compiling single-file, multi-file or directory embedding into embed.FS类型变量orstring/[]byte变量
  • The embed.FS embedded file system provides three methods
    • read the specified directoryfunc (f FS) ReadDir(name string) ([]fs.DirEntry, error)
    • read the specified filefunc (f FS) ReadFile(name string) ([]byte, error)
    • Open the specified filefunc (f FS) Open(name string) (fs.File, error)

Gin project as an example

* main.go
* go.mod
* static
    * js
    * css
* template
    * fragment
        * header.html
        * footer.html
    * content
        * home
            * index.html

filesystem embedded global variables

//go:embed static
var staticFS embed.FS //static目录嵌入staticFS变量

//go:embed template
var templateFS embed.FS //template目录嵌入templateFS变量

Using the Embed file system

func init() {
	router = gin.Default()

	//使用嵌入式文件系统启动静态文件服务
	subStatic, _ := fs.Sub(staticFS, "static")
	router.StaticFS("/static", http.FS(subStatic))

	//使用嵌入式文件系统加载模板
	router.HTMLRender = loadTemplates()
}

func main() {
	router.GET("/home/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "home/index.html", gin.H{})
	})
}

//自定义模板引擎实现多模板功能,模板内容从嵌入式文件系统提取
//依赖github.com/gin-contrib/multitemplate
func loadTemplates() multitemplate.Renderer {
	r := multitemplate.NewRenderer()

	var fragments string
	fragmentFiles, _ := templateFS.ReadDir("template/fragment")
	for _, fragmentFile := range fragmentFiles {
		fragmentFilePath := path.Join("template/fragment", fragmentFile.Name())
		fragment, _ := templateFS.ReadFile(fragmentFilePath)
		fragments += string(fragment)
	}

	contentDirs, _ := templateFS.ReadDir("template/content")
	for _, contentDir := range contentDirs {
		contentDirPath := path.Join("template/content", contentDir.Name())
		contentFiles, _ := templateFS.ReadDir(contentDirPath)

		for _, contentFile := range contentFiles {
			contentFilePath := path.Join(contentDirPath, contentFile.Name())
			tplName := strings.TrimPrefix(contentFilePath, "template/content/")
			content, _ := templateFS.ReadFile(contentFilePath)
			r.AddFromString(tplName, fragments+string(content))
		}
	}

	return r
}
{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324040514&siteId=291194637