绕过 Golang 的 HTTP 处理程序。

huangapple go评论83阅读模式
英文:

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.HandleFunchttp.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)

huangapple
  • 本文由 发表于 2017年3月2日 23:12:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/42559073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定