英文:
Bypass golang http handler
问题
假设我有以下代码:
handler := middleware1.New(
    middleware2.New(
        middleware3.New(
            middleware4.New(
                NewHandler()
            ),
        ),
    ),
)
http.ListenAndServe(":8080", handler)
其中handler包含大量的中间件。
现在我想创建一个自定义的端点,它将跳过所有的中间件,使得serveHTTP()函数内部的内容都不会被执行:
http.HandleFunc("/testing", func(
    w http.ResponseWriter,
    r *http.Request,
) {
    fmt.Fprintf(w, "it works!")
    return
})
http.ListenAndServe(":8080", handler)
但是这样做不起作用,/testing永远不会被访问到。理想情况下,我不想修改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:
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. Ideally, I don't want to modify handler at all, is that possible?
答案1
得分: 2
你可以使用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)
使用http.HandleFunc和http.Handle函数将使用http.DefaultServeMux实现相同的结果,此时你可以将ListenAndServe的处理程序参数留空。
英文:
You can use an http.ServeMux to route requests to the correct handler:
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.
答案2
得分: 1
尝试这个,ListenAndServe处理程序通常为nil。
http.Handle("/", handler)
http.HandleFunc("/testing", func(
    w http.ResponseWriter,
    r *http.Request,
) {
    fmt.Fprintf(w, "it works!")
    return
})
http.ListenAndServe(":8080", nil)
英文:
try this, ListenAndServe handler is usually nil.
http.Handle("/", handler)
http.HandleFunc("/testing", func(
    w http.ResponseWriter,
    r *http.Request,
) {
    fmt.Fprintf(w, "it works!")
    return
})
http.ListenAndServe(":8080", nil)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论