Golang 发布1.16,如今通过//go:embed
注解内嵌资源文件并打包到二进制文件,关于//go:embed
的使用网上很多教程,我想也不需要我在此在啰嗦一遍,今天的重点:用go开发网站时候内嵌的css、html、js以及图片等资源如何内嵌和渲染到网页。
1. 在没有//go:embed
支持之前的实现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))
}
或许: pattern和prefix的设置可以简化些,比如:
mux.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("static/js/"))))
,
然后URL访问也能简化成:http://localhost:8080/js/bootstrap.bundle.min.js
, 但这不是重点,重点是虽然URL多了一个结点,但代码简化了很多还支持了//go:embed
.
测试:浏览器访问http://localhost:8080/web/js/bootstrap.bundle.min.js即可访问到对应文件,想必不太陌生吧。
2. 在支持//go:embed
之后实现方式如下:
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的功劳,实现如下:
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)))
}
有疑问加站长微信联系(非本文作者)