go 1.16 embed 實現(xiàn)資源文件(html, css, js等)內嵌

??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)))
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容