go - go 1.16 embed - 去除目录名
问题描述
我以前使用statik将文件嵌入到 Go 应用程序中。
使用 Go 1.16,我可以删除该 deps
例如:
//go:embed static
var static embed.FS
fs := http.FileServer(http.FS(static))
http.Handle("/", fs)
这将为./static/
目录提供服务http://.../static/
有没有一种方法可以从/
根路径提供该目录,而不需要/static
?
解决方案
使用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))
}
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
推荐阅读
- google-cloud-platform - 要求 BigQuery 视图上的分区过滤器
- javascript - 如何更改我的正则表达式以查找多个网址?
- amazon-web-services - 分析管道中的 AWS IOT 分析 json 格式错误
- angular - 可重用的组件值结转到第 2 页/任何其他页面
- angular - 使用 md-select 禁用提交按钮
- vba - 根据标准将数据从主工作表复制到工作簿
- youtube - 如何使用 API 而不是使用 Google BigQuery 数据传输服务?
- nuget - 无法在 Nuget 中将 Ninject 升级到最新版本
- javascript - 无法调试 JS 错误“t 不是构造函数”
- r - R - 剪切非零值