1 Star 4 Fork 2

tym_hmm / go-helper

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Asset.go 1.08 KB
一键复制 编辑 原始数据 按行查看 历史
天蝎儿 提交于 2022-02-03 15:46 . 增加静态资源打包及模板解析
package AssetHelper
import (
"embed"
"io/fs"
"net/http"
"os"
"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
}
//以下禁止访问目录
as,aerr := file.Stat()
if aerr!=nil{
return nil, os.ErrNotExist
}
if as.IsDir(){
return nil,os.ErrNotExist
}
// Otherwise assume this is a legitimate request routed correctly
return file, err
})
return http.StripPrefix(prefix, http.FileServer(http.FS(handler)))
//return http.FileServer(http.FS(handler))
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/tym_hmm/go-helper.git
git@gitee.com:tym_hmm/go-helper.git
tym_hmm
go-helper
go-helper
v1.1.41

搜索帮助

344bd9b3 5694891 D2dac590 5694891