The introduction

  • Before GO1.16 embed came out, there were a lot of third party to solve the function of static file packaging, its principle is mainly to turn the file into GO source file, the middle has to go through the process of encoding, decoding and so on, the performance is relatively general, so when the official exit embed, I think finally packaging can not copy configuration file
  • Try-holes for everyone, while embedding my own framework and fusing Viper to get configuration files
  • Project making

1, the statement

//go:embed images
var imgs embed.FS

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

//go:embed b.txt
var txt2 string
Copy the code

//go:embed // no Spaces after the embed

2. Directory problems

// Go: Embed does not support relative paths. Only directories or files in the current directory can be obtained

.git.svn.bzr.hg is ignoredCopy the code

Gin framework file server and template usecase

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

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

var f embed.FS

func main(a){

        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")}Copy the code

4. Practical useaddress


1Declare in main2, use the global variable to get f embed3Use global variables where neededCopy the code

5. Relevant references

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

6, the end

Write a bad place to correct, and you encourage it together