//go:embed//go:embed
含有资源文件的demo项目结构
//go:embed
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))
}
mux.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("static/js/"))))http://localhost:8080/js/bootstrap.bundle.min.js//go:embed

测试:浏览器访问http://localhost:8080/web/js/bootstrap.bundle.min.js即可访问到对应文件,想必不太陌生吧。

//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))
}
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)))
}

有疑问加站长微信联系(非本文作者)