From c21f83a36fcc0de3726273e0fe3e77864852d5f4 Mon Sep 17 00:00:00 2001 From: Ewen Quimerc'h <46993939+EwenQuim@users.noreply.github.com> Date: Mon, 13 Nov 2023 21:24:51 +0100 Subject: [PATCH] Grouping returns a sub-router (#24) --- examples/simple-crud/controller/routes.go | 4 ++++ mux.go | 12 ++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/examples/simple-crud/controller/routes.go b/examples/simple-crud/controller/routes.go index 97fb89a8..43b07103 100644 --- a/examples/simple-crud/controller/routes.go +++ b/examples/simple-crud/controller/routes.go @@ -72,4 +72,8 @@ func (rs Ressource) Routes(s *op.Server) { op.Get(groupedS, "/mounted-route", placeholderController) }) }) + + // Grouping with only a prefix and not custom middlewares + apiv2 := op.Group(s, "/v2", nil) + op.Get(apiv2, "/recipes", rs.getAllRecipes) } diff --git a/mux.go b/mux.go index f04300f8..10612022 100644 --- a/mux.go +++ b/mux.go @@ -10,11 +10,15 @@ import ( "github.com/getkin/kin-openapi/openapi3" ) -func Group(s *Server, path string, group func(s *Server)) { +func Group(s *Server, path string, group func(s *Server)) *Server { ss := *s - ss.basePath += path + newServer := &ss + newServer.basePath += path - group(&ss) + if group != nil { + group(newServer) + } + return newServer } type Route[ResponseBody any, RequestBody any] struct { @@ -25,7 +29,7 @@ func Get[T any, B any](s *Server, path string, controller func(Ctx[B]) (T, error return Register[T](s, http.MethodGet, path, controller) } -func Post[T any, B any](s *Server, path string, controller func(Ctx[B]) (T, error)) Route[T, B] { +func Post[T any, B any](s *Server, path string, controller func(Ctx[B]) (T, error), middlewares ...func(http.Handler) http.Handler) Route[T, B] { return Register[T](s, http.MethodPost, path, controller) }