add iris guide builder WithPrefix and WithoutPrefix methods

This commit is contained in:
Gerasimos (Makis) Maropoulos 2023-11-15 12:18:01 +02:00
parent b1f2c24b64
commit e6a12bf776
No known key found for this signature in database
GPG Key ID: B9839E9CD30B7B6B

View File

@ -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
@ -376,6 +381,7 @@ func (s *step5) Middlewares(handlers ...Handler) ServiceGuide {
return &step6{
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 {