我之前使用statik将文件嵌入到 Go 应用程序中。
使用 Go 1.16 我可以删除该依赖项
例如:
//go:embed static
var static embed.FS
fs := http.FileServer(http.FS(static))
http.Handle("/", fs)
Run Code Online (Sandbox Code Playgroud)
这将为./static/目录提供服务http://.../static/
有没有一种方法可以从/根路径提供该目录,而不需要/static?
Pet*_*ter 13
使用fs.Sub:
Sub 返回对应于以 fsys 目录为根的子树的 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))
}
Run Code Online (Sandbox Code Playgroud)
fs.Sub 还可以与http.StripPrefix结合使用来“重命名”目录。例如,要将目录 static “重命名”为 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))))
Run Code Online (Sandbox Code Playgroud)
或者,在静态目录中创建一个 .go 文件并将嵌入指令移至此处 ( //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
Run Code Online (Sandbox Code Playgroud)