plgd-dev / go-coap

Implementation of CoAP Server & Client in Go

Home Page:https://coap.technology

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for Middlewares in mux Router

niondir opened this issue · comments

Is there any plan to support Middlewares in mux.Router?

I imagine some API like in chi.Router (see: https://github.com/go-chi/chi/blob/master/mux.go)
func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler)
func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router
And optionally:
func (mx *Mux) Group(fn func(r Router)) Router

Code seems straight forward and easy to implement.

Currently I use some custom code, but it's not nice to use:

type CoapMiddleWareChain struct {
	HandlerFunctions []func(h mux.HandlerFunc) mux.HandlerFunc
}

func (m *CoapMiddleWareChain) with(next func(h mux.HandlerFunc) mux.HandlerFunc) *CoapMiddleWareChain {
	m.HandlerFunctions = append(m.HandlerFunctions, next)
	return m
}

func (m *CoapMiddleWareChain) wrap(handler mux.HandlerFunc) mux.HandlerFunc {
	if len(m.HandlerFunctions) == 0 {
		return handler
	} else {
		for i := len(m.HandlerFunctions) - 1; i >= 0; i-- {
			handler = m.HandlerFunctions[i](handler)
		}
	}
	return handler
}

@niondir The middleware's are already supported:

func (r *Router) Use(mwf ...MiddlewareFunc) {

eg example:

r.Use(loggingMiddleware)

Do you need something more ?

I need to check that later. Maybe I was missing it in earlier Versions and just missed when it was added.

Actually I very like the inline syntax of chi. But that's very opinionated, I will see how this works out.

Just missing:
func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router

Adding middleware inline is a quiet nice API. Better than wrapping functions in functions.

Ok. So, pls, could you contribute the function? Thx

Need to find some time but I will if nobody else does before me :)