mirror of
https://gitee.com/johng/gf
synced 2026-07-03 03:39:35 +08:00
ghttp.Server文件处理完善
This commit is contained in:
@ -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)
|
||||
|
||||
@ -26,7 +26,9 @@ import (
|
||||
// 封装了常用的文件操作方法,如需更详细的文件控制,请查看官方os包
|
||||
|
||||
// 文件分隔符
|
||||
var Separator = string(filepath.Separator)
|
||||
const (
|
||||
Separator = string(filepath.Separator)
|
||||
)
|
||||
|
||||
// 给定文件的绝对路径创建文件
|
||||
func Mkdir(path string) error {
|
||||
|
||||
@ -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()
|
||||
}
|
||||
Reference in New Issue
Block a user