ghttp.Server/gspath包静态文件检索改进

This commit is contained in:
John
2018-08-26 20:29:28 +08:00
parent 53c86966d9
commit 032d73d016
5 changed files with 25 additions and 16 deletions

2
TODO
View File

@ -23,7 +23,7 @@ ghttp增加返回数据压缩机制
检查windows下的平滑重启失效问题
gview中的template标签失效问题
gfile文件stat信息使用gfsnotify进行缓存更新改进
ghttp.Server增加proxy功能特性本地proxy和远程proxy本地即将路由规则映射远程即反向代理
DONE:

View File

@ -59,7 +59,7 @@ const (
type Server struct {
// 基本属性变量
name string // 服务名称,方便识别
paths *gspath.SPath // 静态文件检索对象
paths *gspath.SPath // 静态文件检索对象(类似nginx tryfile功能)
config ServerConfig // 配置对象
servers []*gracefulServer // 底层http.Server列表
methodsMap map[string]struct{} // 所有支持的HTTP Method(初始化时自动填充)

View File

@ -140,13 +140,19 @@ func (s *Server)callServeHandler(h *handlerItem, r *Request) {
}
}
// http server静态文件处理path必须为完整的**绝对路径**
// http server静态文件处理path可以为相对路径也可以为绝对路径
func (s *Server)serveFile(r *Request, path string) {
f, err := os.Open(path)
if os.IsExist(err) {
path = s.paths.Search(path)
if path == "" {
r.Response.WriteStatus(http.StatusNotFound)
return
}
f, err := os.Open(path)
if err != nil {
r.Response.WriteStatus(http.StatusForbidden)
return
}
defer f.Close()
info, _ := f.Stat()
if info.IsDir() {
if s.config.IndexFolder {
@ -158,7 +164,6 @@ func (s *Server)serveFile(r *Request, path string) {
// 读取文件内容返回, no buffer
http.ServeContent(r.Response.Writer, &r.Request, info.Name(), info.ModTime(), f)
}
f.Close()
}
// 目录列表

View File

@ -68,18 +68,22 @@ func (sp *SPath) Add(path string) error {
return errors.New("invalid path:" + path)
}
// 按照优先级搜索文件,返回搜索到的文件绝对路径
// 按照优先级搜索文件,返回搜索到的文件绝对路径,找不到该文件时,返回空字符串
func (sp *SPath) Search(name string) string {
path := sp.cache.Get(name)
if path == "" {
sp.mu.RLock()
for _, v := range sp.paths {
path = gfile.RealPath(v + gfile.Separator + name)
if path != "" && gfile.Exists(path) {
break
// 优先判断是否给定是已经是一个绝对路径
path = gfile.RealPath(name)
if path == "" {
sp.mu.RLock()
for _, v := range sp.paths {
path = gfile.RealPath(v + gfile.Separator + name)
if path != "" && gfile.Exists(path) {
break
}
}
sp.mu.RUnlock()
}
sp.mu.RUnlock()
if path != "" {
sp.cache.Set(name, path)
sp.addMonitor(name, path)

View File

@ -1,10 +1,10 @@
package main
import (
"gitee.com/johng/gf/g/util/gutil"
"gitee.com/johng/gf/g/os/genv"
"fmt"
"gitee.com/johng/gf/g/os/gfile"
)
func main() {
gutil.Dump(genv.All())
fmt.Println(gfile.RealPath())
}