2 Star 1 Fork 0

mrwhen / gone

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
static.go 1.33 KB
一键复制 编辑 原始数据 按行查看 历史
哎呦-不错的猪公 提交于 2022-12-24 11:40 . fix: 修改module name
package static
import (
"net/http"
"os"
"path"
"strings"
"gitee.com/mrwhen/gone/framework/gin"
)
const INDEX = "index.html"
type ServeFileSystem interface {
http.FileSystem
Exists(prefix string, path string) bool
}
type localFileSystem struct {
http.FileSystem
root string
indexes bool
}
func LocalFile(root string, indexes bool) *localFileSystem {
return &localFileSystem{
FileSystem: gin.Dir(root, indexes),
root: root,
indexes: indexes,
}
}
func (l *localFileSystem) Exists(prefix string, filepath string) bool {
if p := strings.Trim(filepath, prefix); len(p) < len(filepath) {
name := path.Join(l.root, p)
stats, err := os.Stat(name)
if err != nil {
return false
}
if stats.IsDir() {
if !l.indexes {
index := path.Join(name, INDEX)
_, err := os.Stat(index)
if err != nil {
return false
}
}
}
return true
}
return false
}
func ServeRoot(urlPrefix string, root string) gin.HandlerFunc {
return Serve(urlPrefix, LocalFile(root, false))
}
func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
fileserver := http.FileServer(fs)
if urlPrefix != "" {
fileserver = http.StripPrefix(urlPrefix, fileserver)
}
return func(ctx *gin.Context) {
if fs.Exists(urlPrefix, ctx.Request.URL.Path) {
fileserver.ServeHTTP(ctx.Writer, ctx.Request)
ctx.Abort()
}
}
}
Go
1
https://gitee.com/mrwhen/gone.git
git@gitee.com:mrwhen/gone.git
mrwhen
gone
gone
v0.0.1-alpha

搜索帮助