golang1.16开始原生支持文件嵌入
golang1.16开始原生支持文件嵌入,自此外部文件可以在build的时候直接打包进二进制文件中,无需再用第三方工具操作

先贴一段官方介绍

Core library

Embedded Files

The new embed package provides access to files embedded in the program during compilation using the new //go:embed directive.

The go command now supports including static files and file trees as part of the final executable, using the new //go:embed directive. See the documentation for the new embed package for details.

大概的意思就是说,现在我们的核心库embed支持将静态文件打包啦,具体的你们可以看看包里面的说明

包里面乱七八糟的说明也没必要看,直接看例子

// Embedding one file into a string:
//
//	import _ "embed"
//
//	//go:embed hello.txt
//	var s string
//	print(s)
//
// Embedding one file into a slice of bytes:
//
//	import _ "embed"
//
//	//go:embed hello.txt
//	var b []byte
//	print(string(b))
//
// Embedded one or more files into a file system:
//
//	import "embed"
//
//	//go:embed hello.txt
//	var f embed.FS
//	data, _ := f.ReadFile("hello.txt")
//	print(string(data))

// import "embed"
// content holds our static web server content.
//go:embed image/* template/*
//go:embed html/index.html
// var content embed.FS

看着挺骚的,可以直接注入到字节,字符串,embed.FS中,还可以批量关联文件夹文件,测试一下

示例


Last modified on 2021-02-18