【发布时间】:2018-02-21 06:16:47
【问题描述】:
我已经使用适配器模式创建了中间件。我的中间件之一是用于身份验证。因此,如果用户未获得授权,那么我必须向用户发回响应,并且不应调用下一个中间件。
// Adapter type
type Adapter func(http.Handler) http.Handler
// Adapt func
func Adapt(h http.Handler, adapters ...Adapter) http.Handler {
// Call all middleware
for _, adapter := range adapters {
h = adapter(h)
}
return h
}
// CheckAuth middleware
func CheckAuth() Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get Authorization token from the header
// Validate the token
// if valid token then call h.ServeHTTP(w, r)
// else send response 401 to the user,
if(validUser){
h.ServeHTTP(w, r)
}else{
fmt.Fprintf(w, "Unauthorized")
}
return h
}
}
}
http.Handle("/", Adapt(indexHandler, AddHeader(),
CheckAuth(),
CopyMgoSession(db),
Notify(logger),
)
在 CheckAuth 中间件中,我仅在用户获得授权时才调用 h.ServeHTTP(w, r),因此对于 else 条件,我们还需要打破 Adapt 函数的 for 循环,否则它甚至会调用下一个中间件发送响应后。
如果有其他方法可以处理这种情况,请告诉我。
【问题讨论】:
-
你不需要打破循环。在调用 HandlerFunc 时,循环已经完成了很长时间。直接返回而不调用 h.ServeHTTP。
-
嗨@Peter 你能解释一下,如果有 3 个中间件,我将如何从中间件 2 发回响应
标签: go middleware