Golang_embed简单介绍

最近需要使用 golang1.16 中的功能 embed ,本文简单记录下 embed 的使用。 embed 介绍 Go 1.16 引入了embed包,允许我们在编译时将静态文件(例如 .go、.html、.css、.js 等)嵌入到 Go 源文件中。这在构建静态网站、单页应用程序(SPA)和其他项目时非常有用。 主要有几个优点: 方便部署:不需要再部署静态资源文件,所有的资源都直接嵌入到可执行文件中。 安全:用户无法直接访问或修改嵌入的文件。 版本管理:和Go代码一起版本控制。 使用 嵌入为字符串 可以将文件内容保存到字符串变量中。 1 2 3 4 5 6 7 8 9 10 11 12 13 package main import ( _ "embed" "fmt" ) //go:embed hello.txt var s string func main() { fmt.Println(s) } 文件路径下有个 hello.txt,内容如下:hello, overstarry,代码运行输出:hello, overstarry 保存为 []bytes 还可以将文件内容保存为 []bytes变量 1 2 3 4 5 6 7 8 9 10 11 12 13 package main import ( _ "embed" "fmt" ) //go:embed hello....

August 5, 2023 · 2 min · overstarry