源代码位置:

https://github.com/gogf/gf-demos/tree/master/app/service/middleware

跨域处理

允许跨域请求。

  1. // 允许接口跨域请求
  2. func (s *serviceMiddleware) CORS(r *ghttp.Request) {
  3. r.Response.CORSDefault()
  4. r.Middleware.Next()
  5. }

鉴权处理

只有在用户登录后才可通过。

  1. // 鉴权中间件,只有登录成功之后才能通过
  2. func (s *serviceMiddleware) Auth(r *ghttp.Request) {
  3. if User.IsSignedIn(r.Context()) {
  4. r.Middleware.Next()
  5. } else {
  6. r.Response.WriteStatus(http.StatusForbidden)
  7. }
  8. }

上下文注入

前一章节已介绍过。

Content Menu