ghttp.Server文件处理完善

This commit is contained in:
John
2018-04-19 14:58:25 +08:00
parent 6f031a1a72
commit 3a3c35d28a
3 changed files with 22 additions and 22 deletions

View File

@ -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)

View File

@ -26,7 +26,9 @@ import (
// 封装了常用的文件操作方法如需更详细的文件控制请查看官方os包
// 文件分隔符
var Separator = string(filepath.Separator)
const (
Separator = string(filepath.Separator)
)
// 给定文件的绝对路径创建文件
func Mkdir(path string) error {

View File

@ -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()
}