修复静态资源访问错误的问题

This commit is contained in:
fcl 2025-08-18 10:43:10 +08:00
parent bfc15136fd
commit a30d5783ae
1 changed files with 12 additions and 7 deletions

View File

@ -130,11 +130,11 @@ func (s *Server) shouldCompress(req *http.Request) bool {
return false return false
} }
func (s *Server) staticHandle(ctx *gin.Context, fp http.File) { func (s *Server) staticHandle(ctx *gin.Context, fp http.File) bool {
uri := path.Clean(ctx.Request.URL.Path) uri := path.Clean(ctx.Request.URL.Path)
fi, err := fp.Stat() fi, err := fp.Stat()
if err != nil { if err != nil {
return return false
} }
if !fi.IsDir() { if !fi.IsDir() {
//https://github.com/gin-contrib/gzip //https://github.com/gin-contrib/gzip
@ -162,19 +162,24 @@ func (s *Server) staticHandle(ctx *gin.Context, fp http.File) {
} }
http.ServeContent(ctx.Writer, ctx.Request, path.Base(uri), s.fs.modtime, fp) http.ServeContent(ctx.Writer, ctx.Request, path.Base(uri), s.fs.modtime, fp)
ctx.Abort() ctx.Abort()
return true
} }
func (s *Server) notFoundHandle(ctx *gin.Context) { func (s *Server) notFoundHandle(ctx *gin.Context) {
if s.fs != nil && ctx.Request.Method == http.MethodGet { if s.fs != nil && ctx.Request.Method == http.MethodGet {
uri := path.Clean(ctx.Request.URL.Path) uri := path.Clean(ctx.Request.URL.Path)
if fp, err := s.fs.Open(uri); err == nil { if fp, err := s.fs.Open(uri); err == nil {
s.staticHandle(ctx, fp) defer fp.Close()
fp.Close() if s.staticHandle(ctx, fp) {
return
}
} else { } else {
//如果找到对应的压缩文件, 返回压缩文件 //if found compress file
if fp, err := s.fs.Open(uri + ".gz"); err == nil { if fp, err := s.fs.Open(uri + ".gz"); err == nil {
s.staticHandle(ctx, fp) defer fp.Close()
fp.Close() if s.staticHandle(ctx, fp) {
return
}
} }
} }
} }