From 3a3c35d28a9d525a9560ff82d38ac74403c33539 Mon Sep 17 00:00:00 2001 From: John Date: Thu, 19 Apr 2018 14:58:25 +0800 Subject: [PATCH] =?UTF-8?q?ghttp.Server=E6=96=87=E4=BB=B6=E5=A4=84?= =?UTF-8?q?=E7=90=86=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- g/net/ghttp/http_server_handler.go | 18 +++++++++++++----- g/os/gfile/gfile.go | 4 +++- geg/other/test.go | 22 ++++++---------------- 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/g/net/ghttp/http_server_handler.go b/g/net/ghttp/http_server_handler.go index eaccc7c72..4389ac6d6 100644 --- a/g/net/ghttp/http_server_handler.go +++ b/g/net/ghttp/http_server_handler.go @@ -15,8 +15,8 @@ import ( "strings" "net/url" "net/http" - "path/filepath" "gitee.com/johng/gf/g/os/gfile" + "gitee.com/johng/gf/g/util/gregx" "gitee.com/johng/gf/g/encoding/ghtml" ) @@ -77,14 +77,22 @@ func (s *Server)callHandler(h *HandlerItem, r *Request) { // 处理静态文件请求 func (s *Server)serveFile(r *Request) { - uri := r.URL.String() + uri := r.URL.Path if s.config.ServerRoot != "" { // 获取文件的绝对路径 - path := strings.TrimRight(s.config.ServerRoot, string(filepath.Separator)) + path := strings.TrimRight(s.config.ServerRoot, gfile.Separator) + if gfile.Separator != "/" { + uri = strings.Replace(uri, "/", gfile.Separator, -1) + } path = path + uri path = gfile.RealPath(path) if path != "" { - s.doServeFile(r, path) + // 文件/目录访问安全限制:服务的路径必须在ServerRoot下,否则会报错 + if gregx.IsMatchString("^" + s.config.ServerRoot, path) { + s.doServeFile(r, path) + } else { + r.Response.WriteStatus(http.StatusForbidden) + } } else { r.Response.WriteStatus(http.StatusNotFound) } @@ -103,7 +111,7 @@ func (s *Server)doServeFile(r *Request, path string) { if info.IsDir() { if len(s.config.IndexFiles) > 0 { for _, file := range s.config.IndexFiles { - fpath := path + "/" + file + fpath := path + gfile.Separator + file if gfile.Exists(fpath) { f.Close() s.doServeFile(r, fpath) diff --git a/g/os/gfile/gfile.go b/g/os/gfile/gfile.go index e78a4259c..bdbc4a1e0 100644 --- a/g/os/gfile/gfile.go +++ b/g/os/gfile/gfile.go @@ -26,7 +26,9 @@ import ( // 封装了常用的文件操作方法,如需更详细的文件控制,请查看官方os包 // 文件分隔符 -var Separator = string(filepath.Separator) +const ( + Separator = string(filepath.Separator) +) // 给定文件的绝对路径创建文件 func Mkdir(path string) error { diff --git a/geg/other/test.go b/geg/other/test.go index 8bf6bd142..cb468f30c 100644 --- a/geg/other/test.go +++ b/geg/other/test.go @@ -1,23 +1,13 @@ package main import ( - "fmt" + "gitee.com/johng/gf/g/net/ghttp" ) - -type T struct { - name string -} - - -func (t *T) swap(t2 *T) { - *t = &t2 -} - func main() { - t1 := &T{"john"} - t2 := &T{"smith"} - t2.swap(t2) - - fmt.Println(t1) + s := ghttp.GetServer() + s.SetServerRoot("/home/john/Documents") + s.SetIndexFolder(true) + s.SetPort(8199) + s.Run() } \ No newline at end of file