You are viewing an old version of this page. View the current version.
Compare with Current View Page History
« Previous Version 7 Next »
Exit
ExitAll
ExitHook
return
HOOK
由于ExitAll和ExitHook方法在应用层比较少用,因此这里仅介绍Exit方法的使用。
Exit*流程退出特性底层采用的是panic...recover...机制来实现的,通过损耗大约几十纳秒(ns)的CPU开销来提高易用性。
Exit*
panic...recover...
ns
CPU
package main import ( "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" ) func main() { s := g.Server() s.BindHandler("/", func(r *ghttp.Request) { if r.GetInt("type") == 1 { r.Response.Writeln("john") } r.Response.Writeln("smith") }) s.SetPort(8199) s.Run() }
执行后,我们访问 http://127.0.0.1:8199/?type=1 ,可以看到页面输出了:
john smith
我们将以上代码稍微调整一下:
package main import ( "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" ) func main() { s := g.Server() s.BindHandler("/", func(r *ghttp.Request) { if r.GetInt("type") == 1 { r.Response.Writeln("john") r.Exit() } r.Response.Writeln("smith") }) s.SetPort(8199) s.Run() }
执行后,我们再次访问 http://127.0.0.1:8199/?type=1 ,可以看到页面输出了:
john
此外,Response对象中提供了很多Write*Exit的方法,表示输出内容后立即调用Exit方法退出当前服务方法。
Response
Write*Exit