diff --git a/g/frame/gmvc/controller.go b/g/frame/gmvc/controller.go index 0f9a7ca13..9d79771ef 100644 --- a/g/frame/gmvc/controller.go +++ b/g/frame/gmvc/controller.go @@ -36,4 +36,9 @@ func (c *Controller) Shut(r *ghttp.Request) { } +// 推出请求执行 +func (c *Controller) Exit() { + c.Request.Exit() +} + diff --git a/g/net/ghttp/http_request.go b/g/net/ghttp/http_request.go index 4723208d6..d8ad4b478 100644 --- a/g/net/ghttp/http_request.go +++ b/g/net/ghttp/http_request.go @@ -20,6 +20,7 @@ type Request struct { parsedGet *gtype.Bool // GET参数是否已经解析 parsedPost *gtype.Bool // POST参数是否已经解析 values map[string][]string // GET参数 + exit *gtype.Bool // 是否退出当前请求流程执行 Id int // 请求id(唯一) Server *Server // 请求关联的服务器对象 Cookie *Cookie // 与当前请求绑定的Cookie对象(并发安全) @@ -33,6 +34,7 @@ func newRequest(s *Server, r *http.Request, w http.ResponseWriter) *Request { parsedGet : gtype.NewBool(), parsedPost : gtype.NewBool(), values : make(map[string][]string), + exit : gtype.NewBool(), Id : s.servedCount.Add(1), Server : s, Request : *r, @@ -285,5 +287,15 @@ func (r *Request) GetJson() *gjson.Json { return nil } +// 退出当前请求执行,原理是在Request.exit做标记,由服务逻辑流程做判断,自行停止 +func (r *Request) Exit() { + r.exit.Set(true) +} + +// 判断当前请求是否停止执行 +func (r *Request) IsExit() bool { + return r.exit.Val() +} + diff --git a/g/net/ghttp/http_server_handler.go b/g/net/ghttp/http_server_handler.go index 03fcbf129..968c86399 100644 --- a/g/net/ghttp/http_server_handler.go +++ b/g/net/ghttp/http_server_handler.go @@ -60,18 +60,19 @@ func (s *Server)handleRequest(w http.ResponseWriter, r *http.Request) { // 初始化控制器 func (s *Server)callHandler(h *HandlerItem, r *Request) { - // 请求处理 - if h.faddr == nil { // 新建一个控制器对象处理请求 c := reflect.New(h.ctype) c.MethodByName("Init").Call([]reflect.Value{reflect.ValueOf(r)}) - c.MethodByName(h.fname).Call(nil) + if !r.IsExit() { + c.MethodByName(h.fname).Call(nil) + } c.MethodByName("Shut").Call([]reflect.Value{reflect.ValueOf(r)}) } else { - h.faddr(r) + if !r.IsExit() { + h.faddr(r) + } } - } // 处理静态文件请求 diff --git a/geg/frame/mvc/controller/demo/exit.go b/geg/frame/mvc/controller/demo/exit.go new file mode 100644 index 000000000..e3199c7e7 --- /dev/null +++ b/geg/frame/mvc/controller/demo/exit.go @@ -0,0 +1,24 @@ +package demo + +import ( + "gitee.com/johng/gf/g/net/ghttp" + "gitee.com/johng/gf/g/frame/gmvc" +) + +type ControllerExit struct { + gmvc.Controller +} + +func (c *ControllerExit) Init(r *ghttp.Request) { + c.Controller.Init(r) + c.Response.Write("exit, it will not print \"show\"") + c.Request.Exit() +} + +func (c *ControllerExit) Show() { + c.Response.Write("show") +} + +func init() { + ghttp.GetServer().BindController("/exit", &ControllerExit{}) +}