Skip to main content

Middleware

Middleware (interceptor) intercepts requests and responses during their processing to perform certain operations. Common use cases include authentication before requests and wrapping response data after requests.

Middleware is defined similarly to regular route functions, but they include Next() for routing pass-through.

func MiddleWare(r *ghttp.Request) {
r.Middleware.Next()
}

Pre-Request Middleware

Middleware that operates before executing specific route functions is called pre-request middleware. For example, authentication middleware:

func (s *sMiddleware) Auth(r *ghttp.Request) {
user := service.Session().GetUser(r.Context())
if user.Id == 0 {
_ = service.Session().SetNotice(r.Context(), &model.SessionNotice{
Type: consts.SessionNoticeTypeWarn,
Content: "Not logged in or session expired, please log in again.",
})
// Only GET requests support saving the current URL for subsequent redirection after login.
if r.Method == "GET" {
_ = service.Session().SetLoginReferer(r.Context(), r.GetUrl())
}
// Handle different response data structures based on the current request method
if r.IsAjaxRequest() {
response.JsonRedirectExit(r, 1, "", s.LoginUrl)
} else {
r.Response.RedirectTo(s.LoginUrl)
}
}
r.Middleware.Next()
}

Post-Request Middleware

Middleware that operates after executing route functions is called post-request middleware. For example, middleware that wraps the response data format:

// Response handling middleware
func (s *sMiddleware) ResponseHandler(r *ghttp.Request) {
r.Middleware.Next()

// If there is already content in the response, the middleware does nothing
if r.Response.BufferLength() > 0 {
return
}

var (
err = r.GetError()
res = r.GetHandlerResponse()
code gcode.Code = gcode.CodeOK
)
if err != nil {
code = gerror.Code(err)
if code == gcode.CodeNil {
code = gcode.CodeInternalError
}
if r.IsAjaxRequest() {
response.JsonExit(r, code.Code(), err.Error())
} else {
service.View().Render500(r.Context(), model.View{
Error: err.Error(),
})
}
} else {
if r.IsAjaxRequest() {
response.JsonExit(r, code.Code(), "", res)
} else {
// Do nothing; business APIs handle template rendering success logic.
}
}
}

The definition of middleware is essentially as follows:

func MiddleWare(r *ghttp.Request) {
// Pre-request middleware
r.Middleware.Next()
// Post-request middleware
}

SetCtxVar/GetCtxVar

To pass parameters during certain request processes, you can use SetCtxVar/GetCtxVar.

For example:

func MiddleWare(r *ghttp.Request) {
r.SetCtxVar("UserName", "陆玲珑")
r.Middleware.Next()
}

To retrieve in specific route functions:

UserName := r.GetCtxVar("UserName")