go1.16 embed与gin的结合使用|Go主题月

4,448 阅读1分钟

引言

  • 在go1.16的embed出来之前,有很多第3方解决静态文件打包的功能,其原理主要是将文件转成go源码文件,中间还要经过编码, 解码等等过程,性能比较一般,所以在官方退出embed的时候,我就在想终于打包的时候可以不copy配置文件了
  • 给大家踩踩坑,同时嵌入我自己的框架中,融合viper获取配置文件
  • 项目github

1、声明

//go:embed images
var imgs embed.FS

//go:embed a.txt
var txt []byte

//go:embed b.txt
var txt2 string

//go:embed //之后不能有空格

2、目录问题

//go:embed 不支持相对路径,只能获取当前目录下的目录或文件

.git
.svn
.bzr
.hg

会忽略

3、gin框架文件服务器以及模板使用 案例

import (
	"embed"
	"fmt"
	"html/template"
	"net/http"

	"github.com/gin-gonic/gin"
)
//go:embed static templates

var f embed.FS

func main(){

        router := gin.Default()
	templ := template.Must(template.New("").ParseFS(f, "templates/*.html"))
	router.SetHTMLTemplate(templ)

	// example: /public/static/js/1.js
	router.StaticFS("/public", http.FS(f))

	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "Embed Demo",
		})
	})

	router.GET("/foo", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title": "Foo Bar",
		})
	})

	router.Run(":9080")
}


4、实践使用 地址


1、在main声明
2、使用全局变量获取f embed.FS
3、在需要的地方使用全局变量

5、相关参考

  1. www.cnblogs.com/apocelipes/…
  2. blog.csdn.net/flysnow_org…

6、结尾

写的不好的地方给指正,与诸君共勉之