1

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?

3
  • 2
    http.HandleFunc applies to the DefaultServeMux, not your handler. Do you want to add handler to a ServeMux or do you want to add /testing to your handler? Commented Mar 2, 2017 at 15:16
  • @JimB Adding handler to ServeMux seems to be better solution, right? Because adding /testing to handler won't skip middleware, am I right? Commented Mar 2, 2017 at 15:35
  • Yes, if handler doesn't do any muxing before the middleware, then you need to do it separately -- a ServeMux (or any muxer/router package) can do that for you. Commented Mar 2, 2017 at 15:42

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is exactly what I was looking for, thanks!
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.