简体   繁体   English

绕过golang http处理程序

[英]Bypass golang http handler

Let's say I have code like this 假设我有这样的代码

handler := middleware1.New(
    middleware2.New(
        middleware3.New(
            middleware4.New(
                NewHandler()
            ),
        ),
    ),
)
http.ListenAndServe(":8080", handler)

where handler has tons of middleware. 处理程序有大量的中间件。

Now I want to create custom endpoint, which will skip all the middleware, so nothing what's inside serveHTTP() functions is executed: 现在我想创建自定义端点,它将跳过所有中间件,因此执行serveHTTP()函数内部没有任何内容:

http.HandleFunc("/testing", func(
    w http.ResponseWriter,
    r *http.Request,
) {
    fmt.Fprintf(w, "it works!")
    return
})
http.ListenAndServe(":8080", handler)

But this doesn't work and /testing is never reached. 但这不起作用,并且/testing永远不会达到。 Ideally, I don't want to modify handler at all, is that possible? 理想情况下,我根本不想修改handler ,这可能吗?

You can use an http.ServeMux to route requests to the correct handler: 您可以使用http.ServeMux将请求路由到正确的处理程序:

m := http.NewServeMux()
m.HandleFunc("/testing", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "it works!")
    return
})
m.Handle("/", handler)

http.ListenAndServe(":8080", m)

Using the http.HandleFunc and http.Handle functions will accomplish the same result using the http.DefaultServerMux , in which case you would leave the handler argument to ListenAndServe as nil . 使用http.HandleFunchttp.Handle功能将实现使用相同的结果http.DefaultServerMux ,在这种情况下,你会离开的处理器参数ListenAndServe作为nil

try this, ListenAndServe handler is usually nil. 试试这个,ListenAndServe处理程序通常是零。

http.Handle("/", handler)

http.HandleFunc("/testing", func(
    w http.ResponseWriter,
    r *http.Request,
) {
    fmt.Fprintf(w, "it works!")
    return
})
http.ListenAndServe(":8080", nil)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM