我想根据特定条件有条件地添加 http 处理程序
func ConditionalCheck(arg string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
check, ok := ctx.Value("specific").(bool);
if check {
SpecificCheck(arg)
} else {
next.ServeHTTP(w, r)
}
})
}
}
func SpecificCheck(arg string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// something
next.ServeHTTP(w, r)
})
}
}
chain := alice.New(ConditionalCheck, .........)
当我测试时,SpecificCheck HandlerFunc 没有被调用。 我如何根据条件链接它?
最佳答案
SepecificCheck
仅返回一个函数,该函数接受一个处理程序并返回另一个处理程序,它不会执行任何返回的对象。如果您想执行这些对象,则必须显式执行,例如
SepecificCheck(arg)(next).ServeHTTP(w, r)
上面立即调用 SepecificCheck
返回的中间件函数,然后在该中间件函数返回的处理程序上调用 ServeHTTP
方法。
然后更新后的 ConditionalCheck
将如下所示:
func ConditionalCheck(arg string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
check, ok := ctx.Value("specific").(bool)
if check {
SpecificCheck(arg)(next).ServeHTTP(w, r)
} else {
next.ServeHTTP(w, r)
}
})
}
}
关于http - golang 中 http 处理程序的条件链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70077038/