From e6a12bf776663e628445ae0b5787364ee8adf2af Mon Sep 17 00:00:00 2001 From: "Gerasimos (Makis) Maropoulos" Date: Wed, 15 Nov 2023 12:18:01 +0200 Subject: [PATCH] add iris guide builder WithPrefix and WithoutPrefix methods --- iris_guide.go | 50 +++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/iris_guide.go b/iris_guide.go index aa5c49d1..9be3d994 100644 --- a/iris_guide.go +++ b/iris_guide.go @@ -270,10 +270,15 @@ type ( ServiceGuide interface { // Deferrables registers one or more functions to be ran when the server is terminated. Deferrables(closers ...func()) ServiceGuide + // Prefix sets the API Party prefix path. + // Usage: WithPrefix("/api") + WithPrefix(prefixPath string) ServiceGuide + // WithoutPrefix disables the API Party prefix path. + // Usage: WithoutPrefix() + WithoutPrefix() ServiceGuide // Services registers one or more dependencies that APIs can use. Services(deps ...interface{}) ApplicationBuilder } - // ApplicationBuilder is the final step of the Guide. // It is used to register APIs controllers (PartyConfigurators) and // its Build, Listen and Run methods configure and build the actual Iris application @@ -375,7 +380,8 @@ func (s *step5) Middlewares(handlers ...Handler) ServiceGuide { s.middlewares = handlers return &step6{ - step5: s, + step5: s, + prefix: getDefaultAPIPrefix(), } } @@ -387,6 +393,10 @@ type step6 struct { closers []func() // derives from "deps". configuratorsAsDeps []Configurator + + // API Party optional prefix path. + // If this is nil and prefix is empty then it defaults to "/api" in order to keep backwards compatibility. + prefix *string } func (s *step6) Deferrables(closers ...func()) ServiceGuide { @@ -394,6 +404,39 @@ func (s *step6) Deferrables(closers ...func()) ServiceGuide { return s } +var defaultAPIPrefix = "/api" + +func getDefaultAPIPrefix() *string { + return &defaultAPIPrefix +} + +// WithPrefix sets the API Party prefix path. +// Usage: WithPrefix("/api"). +func (s *step6) WithPrefix(prefixPath string) ServiceGuide { + *s.prefix = prefixPath + return s +} + +// WithoutPrefix disables the API Party prefix path. +// Usage: WithoutPrefix() +func (s *step6) WithoutPrefix() ServiceGuide { + s.prefix = nil + return s +} + +func (s *step6) getPrefix() string { + if s.prefix == nil { // if WithoutPrefix called then API has no prefix. + return "" + } + + apiPrefix := *s.prefix + if apiPrefix == "" { // if not nil but empty then it defaults to "/api". + apiPrefix = defaultAPIPrefix + } + + return apiPrefix +} + func (s *step6) Services(deps ...interface{}) ApplicationBuilder { s.deps = deps for _, d := range deps { @@ -502,8 +545,9 @@ func (s *step7) Build() *Application { app.EnsureStaticBindings().RegisterDependency(deps...) } + apiPrefix := s.step6.getPrefix() for prefix, c := range s.m { - app.PartyConfigure("/api"+prefix, c...) + app.PartyConfigure(apiPrefix+prefix, c...) } for _, route := range s.handlers {