Chi: http.Handler vs http.HandlerFunc

Created on 30 Aug 2016  路  7Comments  路  Source: go-chi/chi

I couldn't grep it in the source code,

Is there a way to handle http.Handler using chi.NewRouter().Get(...) or Post(...)?

Should there be a GetFunc(pattern string, h http.HandlerFunc) and Get(pattern string, h http.Handler)?

If I have to choose one, http.Handler is more flexible than its func alternative.

Most helpful comment

Since http.HandlerFunc implements http.Handler, shouldn't all the method functions take an http.Handler instead? This is probably a stretch WRT compatibility, but it would make more sense to structure chi routers around interfaces, rather than around functions.

All 7 comments

Hi,
as a workaround you can set up the route like this:

chi.NewRouter().Get(http.HandlerFunc(yourHandler.ServeHTTP))

hey @didip - yea you can do:chi.NewRouter().Get(yourHander.ServeHTTP)

Oh, TIL, they can be casted back and forth. This works too: handler.(http.HandlerFunc).

Thanks for taking the time!

But that said (I am just opening a discussion here), what do you guys think about having GetFunc and Get as new API? It seems cleaner.

@didip yea, I'd rather not do that.. I want to keep Router interface simpler/smaller.

Since http.HandlerFunc implements http.Handler, shouldn't all the method functions take an http.Handler instead? This is probably a stretch WRT compatibility, but it would make more sense to structure chi routers around interfaces, rather than around functions.

This seems like a giant mistake - to tie the methods' first parameter to http.HandlerFunc and not http.Handler. You want the parameter to be an interface type, not a specific implementation of that interface. Same reason why fmt.Fprint* take an io.Writer, not os.Stdout. Any chance this can be fixed in v5? v6?

@dvelitchkov I hear you, but the common case is to attach a func SomeHandler(w http.ResponseWriter, r *http.Request) { .. } method to an endpoint, if I change the parameter to a http.Handler it will require everyone to write, r.Get("/path", http.HandlerFunc(SomeHandler)) which I don't think is better. It's been decided for syntactic sugar reasons this is the more common case.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chenjie4255 picture chenjie4255  路  11Comments

jsadwith picture jsadwith  路  6Comments

EmielM picture EmielM  路  9Comments

MrXu picture MrXu  路  3Comments

gpopovic picture gpopovic  路  5Comments