绕过Golang HTTP处理程序

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?

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.

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)