diff --git a/.example/other/test.go b/.example/other/test.go index 0bc9f57d6..69aa55a6b 100644 --- a/.example/other/test.go +++ b/.example/other/test.go @@ -1,15 +1,43 @@ package main import ( - "fmt" + "net/http" + + "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" ) +func MiddlewareAuth(r *ghttp.Request) { + token := r.Get("token") + if token == "123456" { + r.Middleware.Next() + } else { + r.Response.WriteStatus(http.StatusForbidden) + } +} + +func MiddlewareCORS(r *ghttp.Request) { + r.Response.CORSDefault() + r.Middleware.Next() +} + +func MiddlewareLog(r *ghttp.Request) { + r.Middleware.Next() + g.Log().Println(r.Response.Status, r.URL.Path, r.GetError().Error()) +} + func main() { - s := ghttp.GetServer() - s.BindHandler("/*", func(r *ghttp.Request) { - fmt.Println(r.URL.RawPath) - r.Response.Write(r.GetUrl()) + s := g.Server() + s.SetConfigWithMap(g.Map{ + "AccessLogEnabled": false, + "ErrorLogEnabled": false, + }) + s.BindMiddlewareDefault(MiddlewareLog) + s.Group("/api.v2", func(group *ghttp.RouterGroup) { + group.Middleware(MiddlewareAuth, MiddlewareCORS) + group.ALL("/user/list", func(r *ghttp.Request) { + panic("啊!我出错了!") + }) }) s.SetPort(8199) s.Run() diff --git a/net/ghttp/ghttp_request.go b/net/ghttp/ghttp_request.go index c64db0301..5d970b441 100644 --- a/net/ghttp/ghttp_request.go +++ b/net/ghttp/ghttp_request.go @@ -161,3 +161,9 @@ func (r *Request) GetSessionId() string { func (r *Request) GetReferer() string { return r.Header.Get("Referer") } + +// GetError returns the error occurs in the procedure of the request. +// It returns nil if there's no error. +func (r *Request) GetError() error { + return r.error +}