middleware stacking bug fix

This commit is contained in:
2025-08-16 19:25:00 +05:30
parent 5885b42816
commit ec4a0ac231
4 changed files with 19 additions and 23 deletions

25
mux.go
View File

@@ -4,6 +4,7 @@ import (
"fmt"
"io"
"net/http"
"slices"
"strings"
"sync/atomic"
)
@@ -102,25 +103,19 @@ func (m *Mux) handle(method, pattern string, h http.HandlerFunc, mw ...func(http
path := fmt.Sprintf("%s %s", method, pattern)
if len(mw) > 0 {
mws := make([]func(http.Handler) http.Handler, len(m.middlewares)+len(mw))
copy(mws, m.middlewares)
mws = append(mws, mw...)
m.mux.Handle(path, stack(h, copyMW(m.middlewares, mw)))
} else {
m.mux.Handle(path, stack(m.middlewares, h))
m.mux.Handle(path, stack(h, m.middlewares))
}
m.routes.Add(path)
}
// With adds inline middlewares for an endpoint handler.
func (m *Mux) With(middleware ...func(http.Handler) http.Handler) *Mux {
mws := make([]func(http.Handler) http.Handler, len(m.middlewares)+len(middleware))
copy(mws, m.middlewares)
mws = append(mws, middleware...)
func (m *Mux) With(mw ...func(http.Handler) http.Handler) *Mux {
im := &Mux{
mux: m.mux,
middlewares: mws,
middlewares: copyMW(m.middlewares, mw),
routes: m.routes,
}
@@ -160,3 +155,13 @@ func (m *Mux) PrintRoutes(w io.Writer) {
func (m *Mux) RouteList() []string {
return m.routes.All()
}
func copyMW(a []func(http.Handler) http.Handler, b []func(http.Handler) http.Handler) []func(http.Handler) http.Handler {
if len(b) > 0 {
return slices.Concat(a, b)
}
mws := make([]func(http.Handler) http.Handler, len(a))
copy(mws, a)
return mws
}