使用fs.Sub:
Sub 返回一个对应于以 fsys 的 dir 为根的子树的 FS。
package main
import (
"embed"
"io/fs"
"log"
"net/http"
)
//go:embed static
var static embed.FS
func main() {
subFS, _ := fs.Sub(static, "static")
http.Handle("/", http.FileServer(http.FS(subFS)))
log.Fatal(http.ListenAndServe(":4000", nil))
}
fs.Sub 还可以与http.StripPrefix 结合使用以“重命名”目录。例如,将静态目录“重命名”为 public,这样对 /public/index.html 的请求就会为 static/index.html 服务:
//go:embed static
var static embed.FS
subFS, _ := fs.Sub(static, "static")
http.Handle("/", http.StripPrefix("/public", http.FileServer(http.FS(subFS))))
或者,在静态目录中创建一个 .go 文件并将 embed 指令移到那里 (//go:embed *)。这更接近于 statik 工具所做的事情(它创建一个全新的包),但由于 fs.Sub,通常是不必要的。
// main.go
package main
import (
"my.module/static"
"log"
"net/http"
)
func main() {
http.Handle("/", http.FileServer(http.FS(static.FS)))
log.Fatal(http.ListenAndServe(":4000", nil))
}
// static/static.go
package static
import "embed"
//go:embed *
var FS embed.FS