??Golang 發(fā)布1.16,如今通過//go:embed 注解內嵌資源文件并打包到二進制文件,關于//go:embed的使用網(wǎng)上很多教程,我想也不需要我在此在啰嗦一遍,今天的重點:用go開發(fā)網(wǎng)站時候內嵌的css、html、js以及圖片等資源如何內嵌和渲染到網(wǎng)頁。

含有資源文件的demo項目結構
1. 在沒有//go:embed支持之前的實現(xiàn)serve文件的方式如下:
package main
import (
"log"
"net/http"
)
func main() {
mux := http.DefaultServeMux
mux.Handle("/web/js/", http.StripPrefix("/web/js/", http.FileServer(http.Dir("static/js/"))))
mux.Handle("/web/css/", http.StripPrefix("/web/css/", http.FileServer(http.Dir("static/css/"))))
mux.Handle("/web/img/", http.StripPrefix("/web/img/", http.FileServer(http.Dir("static/img/"))))
log.Fatal(http.ListenAndServe(":8080", mux))
}
這種實現(xiàn)方式需要打包后將資源文件一并拷貝且要求放指定目錄,否則程序找不到對應文件,然后報錯。
或許: pattern和prefix的設置可以簡化些,比如:
mux.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("static/js/")))),
然后URL訪問也能簡化成: http://localhost:8080/js/bootstrap.bundle.min.js, 但這不是重點,重點是雖然URL多了一個結點,但下面的實現(xiàn)代碼簡化了很多還支持了//go:embed.
測試:瀏覽器訪問http://localhost:8080/web/js/bootstrap.bundle.min.js即可訪問到對應文件,想必不太陌生吧。
2. 在支持//go:embed之后實現(xiàn)方式如下:
package main
import (
"embed"
_ "embed"
"log"
"net/http"
)
//go:embed template static
var Assets embed.FS
func main() {
mux := http.DefaultServeMux
mux.Handle("/web/", AssetHandler("/web/", Assets, "./static"))
log.Fatal(http.ListenAndServe(":8080", mux))
}
測試:瀏覽器訪問http://localhost:8080/web/js/bootstrap.bundle.min.js即可訪問到對應文件,訪問url一樣,不同的是資源文件會在go build打包后全部內嵌。
3. 之所embed的資源文件還能被serve,多虧了AssetHandler的功勞,實現(xiàn)如下:
package main
import (
"embed"
"io/fs"
"net/http"
"path"
)
type fsFunc func(name string) (fs.File, error)
func (f fsFunc) Open(name string) (fs.File, error) {
return f(name)
}
// AssetHandler returns an http.Handler that will serve files from
// the Assets embed.FS. When locating a file, it will strip the given
// prefix from the request and prepend the root to the filesystem.
func AssetHandler(prefix string, assets embed.FS, root string) http.Handler {
handler := fsFunc(func(name string) (fs.File, error) {
assetPath := path.Join(root, name)
// If we can't find the asset, fs can handle the error
file, err := assets.Open(assetPath)
if err != nil {
return nil, err
}
// Otherwise assume this is a legitimate request routed correctly
return file, err
})
return http.StripPrefix(prefix, http.FileServer(http.FS(handler)))
}