需求场景
有时候golang打包一个web应用,想html,js,css等也一并打包进去成一个二进制文件,方便做分发
常见的工具
gobindata
https://github.com/go-bindata/go-bindata
[root@workpc ~]# go-bindata -o myfile.go data/
data, err := Asset("pub/style/foo.css")
if err != nil {
// Asset was not found.
}
// use asset data
statik
https://github.com/rakyll/statik
[root@workpc ~]#go get github.com/rakyll/statik
[root@workpc ~]#statik -src=/path/to/your/project/public
import (
"github.com/rakyll/statik/fs"
_ "./statik" // 替换成你刚才生成目录的路径
)
// ...
statikFS, err := fs.New()
if err != nil {
log.Fatal(err)
}
// Serve the contents over HTTP.
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS)))
http.ListenAndServe(":8080", nil)
go1.16版本解决方案
import "embed"
// content 就是我们的静态资源
//go:embed image/* template/*
//go:embed html/index.html
var content embed.FS
//go:embed hello.txt
var s string
print(s)
//go:embed hello.txt
var b []byte
print(string(b))
//go:embed hello.txt
var f embed.FS
data, _ := f.ReadFile("hello.txt")
print(string(data))