http - golang 中 http 处理程序的条件链接

标签 http go httphandler chaining

我想根据特定条件有条件地添加 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/

相关文章:

python - 带有 python 套接字的 HTTP 服务器

http - 如何停用jsp页面内的缓存

java - 在 Spring Integration 中将 HTTP 请求 header 设置为 LinkedList

go - 在 GO 中将多部分形式的数据读取为 []byte

c# - ASP.NET HttpHandler 可以处理 http 400 - 错误请求吗?

go - 我应该在包级别但在 http 处理程序之外声明变量吗?

angular - 是否可以通过使用另一个类中的变量在枚举(调用函数)中拥有计算属性?

go lang version-able 字符串规范化

arrays - Golang中如何返回未知类型的数组?

asp.net - 如何将 HttpHandler 添加到 web.config 中?