From b0a08fbb6ebc19cd49d4fe153d8a255443dbe4b7 Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Mon, 23 Nov 2026 14:46:49 +0000 Subject: [PATCH 1/2] feat(app)!: the app runs from its config, not APP_ENV The app, the scheduler and failed responses each read APP_ENV from the environment. app.New now takes config.App first, so an app cannot be built without one, and hands its environment on: to the scheduler, for commands limited to some environments, and to responses, which say the error behind a failure outside production only (response.ShowErrors). BREAKING CHANGE: app.New takes a config.App as its first argument. --- app/app.go | 14 +++++++---- app/options.go | 2 +- routing/response/options.go | 14 +++++++++-- scheduling/engine.go | 8 ++++--- scheduling/options.go | 8 +++++++ scheduling/scheduling.go | 3 +++ {app => tests/app}/container_test.go | 4 ++-- tests/routing/errors_test.go | 35 +++++++++++++++++++++++++++ tests/scheduling/environment_test.go | 36 ++++++++++++++++++++++++++++ 9 files changed, 112 insertions(+), 12 deletions(-) rename {app => tests/app}/container_test.go (94%) create mode 100644 tests/routing/errors_test.go create mode 100644 tests/scheduling/environment_test.go diff --git a/app/app.go b/app/app.go index 50c6f5d..b33c94f 100644 --- a/app/app.go +++ b/app/app.go @@ -13,14 +13,14 @@ import ( "github.com/gonstruct/core/facades/database" "github.com/gonstruct/core/queueing" "github.com/gonstruct/core/routing" + "github.com/gonstruct/core/routing/response" "github.com/gonstruct/core/scheduling" "github.com/rs/zerolog/log" - - "github.com/gonstruct/validation/env" ) type App struct { + config config.App environment config.Environment ctx context.Context @@ -53,14 +53,20 @@ func Instance() *App { var instance *App -func New(options ...option) *App { +// New builds the application from its config, which the rest of it reads: +// its environment decides which scheduled commands run and whether failed +// responses say their error. +func New(configuration config.App, options ...option) *App { application := &App{ - environment: env.Enum[config.Environment]("APP_ENV"), + config: configuration, + environment: configuration.Environment, ctx: context.Background(), createdAt: time.Now(), console: console.New(), } + response.ShowErrors(configuration.Environment != config.ProductionEnvironment) + for _, option := range options { option(application) } diff --git a/app/options.go b/app/options.go index 9e09338..b575460 100644 --- a/app/options.go +++ b/app/options.go @@ -69,7 +69,7 @@ func WithRouting(options ...routing.Option) option { func WithScheduling(options ...scheduling.Option) option { return func(a *App) { - a.scheduling = scheduling.New(options...) + a.scheduling = scheduling.New(append([]scheduling.Option{scheduling.WithEnvironment(a.environment.String())}, options...)...) a.console.Register("schedule:work", func(*console.Console, []string) error { return a.scheduling.Run() }) } } diff --git a/routing/response/options.go b/routing/response/options.go index 3b5a5ff..04895c3 100644 --- a/routing/response/options.go +++ b/routing/response/options.go @@ -3,8 +3,8 @@ package response import ( "fmt" "net/http" - "os" "sort" + "sync/atomic" "github.com/gonstruct/core/routing/resource" @@ -13,6 +13,16 @@ import ( type ErrorsMap map[string]string +// showErrors is whether a failed response says the error behind it: off +// until the app says otherwise, as it does outside production. +var showErrors atomic.Bool + +// ShowErrors has failed responses say the error behind them, or not. The +// app turns it on outside production. +func ShowErrors(show bool) { + showErrors.Store(show) +} + type value[T any] struct { isSet bool value T @@ -86,7 +96,7 @@ func (options *responseOptions) resolve(context *gin.Context) { context.AbortWithStatusJSON(options.StatusCode, resource.Resource{ "message": resource.When(options.Message.isSet, func() string { return options.Message.value }), "code": resource.When(options.Code.isSet, func() string { return options.Code.value }), - "error": resource.When(options.Error.isSet && os.Getenv("APP_ENV") != "production", func() string { return options.Error.value.Error() }), + "error": resource.When(options.Error.isSet && showErrors.Load(), func() string { return options.Error.value.Error() }), "errors": resource.When(options.Errors.isSet, func() ErrorsMap { return options.Errors.value }), }) diff --git a/scheduling/engine.go b/scheduling/engine.go index 8f594e7..b3eba87 100644 --- a/scheduling/engine.go +++ b/scheduling/engine.go @@ -3,7 +3,6 @@ package scheduling import ( "context" "fmt" - "os" "slices" "time" @@ -35,6 +34,9 @@ func NewSynchronousEngine() *Engine { type Engine struct { gocron.Scheduler + // Environment is the one commands limited to some run in. + Environment string + synchronous bool Commands []command.Command } @@ -50,8 +52,8 @@ func (e *Engine) Command(cmd command.Command, options ...command.Option) { opts := command.NewOptions(options...) - if len(opts.Environments) > 0 && !slices.Contains(opts.Environments, os.Getenv("APP_ENV")) { - log.Info().Msgf("[scheduling] skipping command %s for environment %s", cmd.Name(), os.Getenv("APP_ENV")) + if len(opts.Environments) > 0 && !slices.Contains(opts.Environments, e.Environment) { + log.Info().Msgf("[scheduling] skipping command %s for environment %s", cmd.Name(), e.Environment) return } diff --git a/scheduling/options.go b/scheduling/options.go index f6df823..9082ca7 100644 --- a/scheduling/options.go +++ b/scheduling/options.go @@ -2,6 +2,14 @@ package scheduling type Option func(*Scheduling) +// WithEnvironment is the environment commands limited to some run in. The +// app passes its own. +func WithEnvironment(environment string) Option { + return func(r *Scheduling) { + r.Environment = environment + } +} + func WithSchedulers(schedulers ...func(*Engine)) Option { return func(r *Scheduling) { r.Schedulers = append(r.Schedulers, schedulers...) diff --git a/scheduling/scheduling.go b/scheduling/scheduling.go index 540e7ba..dcb1d3d 100644 --- a/scheduling/scheduling.go +++ b/scheduling/scheduling.go @@ -2,6 +2,8 @@ package scheduling type Scheduling struct { Schedulers []func(*Engine) + // Environment is the one commands limited to some run in. + Environment string } func New(options ...Option) *Scheduling { @@ -19,6 +21,7 @@ func (s *Scheduling) Run() error { if err != nil { return err } + scheduler.Environment = s.Environment for _, f := range s.Schedulers { f(scheduler) diff --git a/app/container_test.go b/tests/app/container_test.go similarity index 94% rename from app/container_test.go rename to tests/app/container_test.go index f9c9c6b..db3826b 100644 --- a/app/container_test.go +++ b/tests/app/container_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/gonstruct/core/app" + "github.com/gonstruct/core/config" ) type service struct{ built int } @@ -13,9 +14,8 @@ type service struct{ built int } // entrypoint does. func boot(t *testing.T, bindings ...app.Binding) { t.Helper() - t.Setenv("APP_ENV", "testing") - app.New(app.WithSingletons(app.Singletons(bindings...))).SetInstance() + app.New(config.App{Environment: config.TestingEnvironment}, app.WithSingletons(app.Singletons(bindings...))).SetInstance() } func TestSingletonBuildsOnceAndShares(t *testing.T) { diff --git a/tests/routing/errors_test.go b/tests/routing/errors_test.go new file mode 100644 index 0000000..bc33541 --- /dev/null +++ b/tests/routing/errors_test.go @@ -0,0 +1,35 @@ +package routing_test + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gonstruct/core/routing" + "github.com/gonstruct/core/routing/response" + + "github.com/gin-gonic/gin" +) + +// A failed response says the error behind it only when the app shows +// errors, as it does outside production. +func TestFailedResponsesShowTheirErrorOnlyWhenAsked(t *testing.T) { + t.Cleanup(func() { response.ShowErrors(false) }) + engine := routing.New(routing.WithRouters(func(engine *routing.Engine) { + engine.GET("/broken", func(*gin.Context) response.Response { + return response.Error(errors.New("the database is down")) + }) + })).Engine() + + for _, show := range []bool{true, false} { + response.ShowErrors(show) + recorder := httptest.NewRecorder() + engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/broken", nil)) + + if said := strings.Contains(recorder.Body.String(), "the database is down"); said != show { + t.Errorf("showing errors %v: the response said it %v: %s", show, said, recorder.Body.String()) + } + } +} diff --git a/tests/scheduling/environment_test.go b/tests/scheduling/environment_test.go new file mode 100644 index 0000000..8c4be8a --- /dev/null +++ b/tests/scheduling/environment_test.go @@ -0,0 +1,36 @@ +package scheduling_test + +import ( + "context" + "testing" + + "github.com/gonstruct/core/scheduling" + "github.com/gonstruct/core/scheduling/command" +) + +type nightly struct{} + +func (nightly) Name() string { return "nightly" } +func (nightly) Handle(context.Context) error { return nil } + +// A command limited to some environments is left out of the others, as the +// app's config says, whatever APP_ENV is. +func TestCommandsRunInTheirEnvironmentsOnly(t *testing.T) { + t.Setenv("APP_ENV", "production") + + for _, each := range []struct { + environment string + registered bool + }{{"production", true}, {"staging", false}} { + engine, err := scheduling.NewEngine() + if err != nil { + t.Fatal(err) + } + engine.Environment = each.environment + engine.Command(nightly{}, command.EveryMinute(), command.Environment[string]("production")) + + if got := len(engine.Jobs()) > 0; got != each.registered { + t.Errorf("in %s: expected registered %v, got %v", each.environment, each.registered, got) + } + } +} From 762e64b09051bff4fcde71a101ff0b267e3c9289 Mon Sep 17 00:00:00 2001 From: Arjen de Vos Date: Mon, 23 Nov 2026 15:57:06 +0000 Subject: [PATCH 2/2] refactor(routing): let the server config say whether failed responses show their error A package-level switch set by app.New was state every request shared. config.Server.ShowErrors now goes on each request's context, where the response reads it, so the app decides it with the rest of the server. --- app/app.go | 6 +----- config/server.go | 3 +++ routing/response/options.go | 20 +++++++++++--------- routing/routing.go | 1 + tests/routing/errors_test.go | 18 ++++++++---------- 5 files changed, 24 insertions(+), 24 deletions(-) diff --git a/app/app.go b/app/app.go index b33c94f..9d97ec9 100644 --- a/app/app.go +++ b/app/app.go @@ -13,7 +13,6 @@ import ( "github.com/gonstruct/core/facades/database" "github.com/gonstruct/core/queueing" "github.com/gonstruct/core/routing" - "github.com/gonstruct/core/routing/response" "github.com/gonstruct/core/scheduling" "github.com/rs/zerolog/log" @@ -54,8 +53,7 @@ func Instance() *App { var instance *App // New builds the application from its config, which the rest of it reads: -// its environment decides which scheduled commands run and whether failed -// responses say their error. +// its environment decides which scheduled commands run. func New(configuration config.App, options ...option) *App { application := &App{ config: configuration, @@ -65,8 +63,6 @@ func New(configuration config.App, options ...option) *App { console: console.New(), } - response.ShowErrors(configuration.Environment != config.ProductionEnvironment) - for _, option := range options { option(application) } diff --git a/config/server.go b/config/server.go index 3f4b20a..b9a573a 100644 --- a/config/server.go +++ b/config/server.go @@ -18,4 +18,7 @@ type Server struct { // TrustedPlatform is the header the platform in front of the server // puts the client's IP in, as gin's TrustedPlatform: none when empty. TrustedPlatform string + // ShowErrors has a failed response say the error behind it: for a + // developer's own machine, never production. + ShowErrors bool } diff --git a/routing/response/options.go b/routing/response/options.go index 04895c3..6840341 100644 --- a/routing/response/options.go +++ b/routing/response/options.go @@ -4,7 +4,6 @@ import ( "fmt" "net/http" "sort" - "sync/atomic" "github.com/gonstruct/core/routing/resource" @@ -13,14 +12,17 @@ import ( type ErrorsMap map[string]string -// showErrors is whether a failed response says the error behind it: off -// until the app says otherwise, as it does outside production. -var showErrors atomic.Bool +// showErrorsKey is where a request keeps whether its failed response says +// the error behind it. +const showErrorsKey = "gonstruct.response.show-errors" -// ShowErrors has failed responses say the error behind them, or not. The -// app turns it on outside production. -func ShowErrors(show bool) { - showErrors.Store(show) +// ShowErrors has the failed responses of the requests it runs before say +// the error behind them, or not: routing runs it as its config says. +func ShowErrors(show bool) gin.HandlerFunc { + return func(context *gin.Context) { + context.Set(showErrorsKey, show) + context.Next() + } } type value[T any] struct { @@ -96,7 +98,7 @@ func (options *responseOptions) resolve(context *gin.Context) { context.AbortWithStatusJSON(options.StatusCode, resource.Resource{ "message": resource.When(options.Message.isSet, func() string { return options.Message.value }), "code": resource.When(options.Code.isSet, func() string { return options.Code.value }), - "error": resource.When(options.Error.isSet && showErrors.Load(), func() string { return options.Error.value.Error() }), + "error": resource.When(options.Error.isSet && context.GetBool(showErrorsKey), func() string { return options.Error.value.Error() }), "errors": resource.When(options.Errors.isSet, func() ErrorsMap { return options.Errors.value }), }) diff --git a/routing/routing.go b/routing/routing.go index e09091b..8443d17 100644 --- a/routing/routing.go +++ b/routing/routing.go @@ -47,6 +47,7 @@ func (r *Routing) Engine() *Engine { server := r.server() router.TrustedPlatform = server.TrustedPlatform + router.Engine.Use(response.ShowErrors(server.ShowErrors)) router.ContextWithFallback = true router.RemoteIPHeaders = []string{ "CF-Connecting-IP", diff --git a/tests/routing/errors_test.go b/tests/routing/errors_test.go index bc33541..f57b9ec 100644 --- a/tests/routing/errors_test.go +++ b/tests/routing/errors_test.go @@ -7,24 +7,22 @@ import ( "strings" "testing" + "github.com/gonstruct/core/config" "github.com/gonstruct/core/routing" "github.com/gonstruct/core/routing/response" "github.com/gin-gonic/gin" ) -// A failed response says the error behind it only when the app shows -// errors, as it does outside production. +// A failed response says the error behind it only when the server's config +// shows errors, as an app does outside production. func TestFailedResponsesShowTheirErrorOnlyWhenAsked(t *testing.T) { - t.Cleanup(func() { response.ShowErrors(false) }) - engine := routing.New(routing.WithRouters(func(engine *routing.Engine) { - engine.GET("/broken", func(*gin.Context) response.Response { - return response.Error(errors.New("the database is down")) - }) - })).Engine() - for _, show := range []bool{true, false} { - response.ShowErrors(show) + engine := routing.New(routing.WithConfig(config.Server{ShowErrors: show}), routing.WithRouters(func(engine *routing.Engine) { + engine.GET("/broken", func(*gin.Context) response.Response { + return response.Error(errors.New("the database is down")) + }) + })).Engine() recorder := httptest.NewRecorder() engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/broken", nil))