chore(cordis): sync Wavelet core/pkg/plugins after W1-W9

This commit is contained in:
ryan
2026-08-30 11:46:58 +08:00
parent dd333643f2
commit e847a7adb3
39 changed files with 1018 additions and 751 deletions
+17
View File
@@ -77,6 +77,8 @@ func (p *Plugin) Apply(ctx *core.Context) error {
InvalidateRuntimeSettings()
})
core.Provide[contracts.CaptchaService](ctx, captchaService{})
// Register HTTP Routes
capGroup := ctx.Router().Group("/api/v1/cap")
{
@@ -85,6 +87,11 @@ func (p *Plugin) Apply(ctx *core.Context) error {
capGroup.POST("/redeem", Redeem)
}
legacy := ctx.Router().Group("/api/cap")
legacy.POST("/challenge", Challenge)
legacy.POST("/redeem", Redeem)
ctx.Router().RegisterWhitelist("/api/cap/challenge", "/api/cap/redeem")
// Register Settings Schemas
ctx.Settings().Register(extpoints.SettingSchema{
Key: "cap.login_enabled",
@@ -103,3 +110,13 @@ func (p *Plugin) Apply(ctx *core.Context) error {
return nil
}
type captchaService struct{}
func (captchaService) VerifyMiddleware(scope string) any {
return VerifyMiddleware(GetDefaultManager(), scope)
}
func (captchaService) ChallengeHandler() any { return Challenge }
func (captchaService) RedeemHandler() any { return Redeem }
@@ -0,0 +1,52 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package cap
import (
"context"
"testing"
"Wavelet/core"
"Wavelet/core/contracts"
)
func TestApplyProvidesCaptchaService(t *testing.T) {
ctx := core.NewContext(context.Background())
if err := New().Apply(ctx); err != nil {
t.Fatal(err)
}
svc, err := core.Inject[contracts.CaptchaService](ctx)
if err != nil || svc == nil {
t.Fatalf("Inject CaptchaService: svc=%v err=%v", svc, err)
}
if svc.ChallengeHandler() == nil || svc.RedeemHandler() == nil {
t.Fatal("handlers must be non-nil")
}
if svc.VerifyMiddleware("login") == nil {
t.Fatal("VerifyMiddleware(login) must be non-nil")
}
}
func TestApplyRegistersUnversionedCapRoutes(t *testing.T) {
ctx := core.NewContext(context.Background())
if err := New().Apply(ctx); err != nil {
t.Fatal(err)
}
want := map[string]bool{
"POST /api/v1/cap/challenge": false,
"POST /api/cap/challenge": false,
"POST /api/cap/redeem": false,
}
for _, rd := range ctx.Router().Routes() {
key := rd.Method + " " + rd.Path
if _, ok := want[key]; ok {
want[key] = true
}
}
for key, ok := range want {
if !ok {
t.Errorf("missing route %s", key)
}
}
}
@@ -231,8 +231,9 @@ func (p *Plugin) Apply(ctx *core.Context) error {
return nil
})
// 9. Register built-in domain events
// 9. Register built-in domain events and provide PushRegistry
service.RegisterCustomEvents()
core.Provide[contracts.PushRegistry](ctx, service.PushRegistryAdapter{})
// 10. Register Settings Schemas
ctx.Settings().Register(extpoints.SettingSchema{
@@ -0,0 +1,54 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package message_gateway_test
import (
"Wavelet/core"
"Wavelet/core/contracts"
"Wavelet/plugins/domain/message_gateway"
"Wavelet/plugins/domain/message_gateway/service"
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestPushRegistry(t *testing.T) {
ctx := core.NewContext(context.Background())
require.NoError(t, message_gateway.New().Apply(ctx))
registry, err := core.Inject[contracts.PushRegistry](ctx)
require.NoError(t, err)
require.NotNil(t, registry)
const key = "test.push_registry.probe"
registry.RegisterBuiltInEvent(contracts.PushEventMeta{
Key: key,
Name: "Push Registry Probe",
Description: "observability probe for contracts.PushRegistry",
DefaultTemplate: contracts.PushNotificationTemplate{
Title: "Probe Title",
Content: "Probe Content",
Level: "INFO",
Ext: map[string]any{"source": "test"},
},
})
found := false
for _, ev := range service.GetBuiltInEvents() {
if ev.Key != key {
continue
}
found = true
assert.Equal(t, "Push Registry Probe", ev.Name)
assert.Equal(t, "observability probe for contracts.PushRegistry", ev.Description)
assert.Equal(t, "Probe Title", ev.DefaultTemplate.Title)
assert.Equal(t, "Probe Content", ev.DefaultTemplate.Content)
assert.Equal(t, "INFO", ev.DefaultTemplate.Level)
assert.Equal(t, map[string]any{"source": "test"}, ev.DefaultTemplate.Ext)
break
}
require.True(t, found, "registered key %q should be visible via GetBuiltInEvents", key)
}
@@ -49,6 +49,31 @@ func GetBuiltInEvents() []model.EventMetadata {
return out
}
// PushRegistryAdapter adapts contracts.PushRegistry onto the built-in event store.
type PushRegistryAdapter struct{}
func (PushRegistryAdapter) RegisterBuiltInEvent(meta contracts.PushEventMeta) {
RegisterBuiltInEvent(eventMetadataFromContract(meta))
}
func (PushRegistryAdapter) SyncEvents(ctx context.Context) error {
return SyncEvents(ctx)
}
func eventMetadataFromContract(meta contracts.PushEventMeta) model.EventMetadata {
return model.EventMetadata{
Key: meta.Key,
Name: meta.Name,
Description: meta.Description,
DefaultTemplate: model.NotificationMessage{
Title: meta.DefaultTemplate.Title,
Content: meta.DefaultTemplate.Content,
Level: meta.DefaultTemplate.Level,
Ext: meta.DefaultTemplate.Ext,
},
}
}
// SyncBuiltInEvents seeds a database row for every registered built-in event.
func SyncBuiltInEvents(ctx context.Context) error {
for _, meta := range GetBuiltInEvents() {
@@ -0,0 +1,97 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package system
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"Wavelet/core"
"github.com/gin-gonic/gin"
)
func TestHealthRouteReturnsOKNil(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx := core.NewContext(context.Background())
if err := New().Apply(ctx); err != nil {
t.Fatal(err)
}
healthHandler := routeHandler(t, ctx, "GET", "/api/health")
routeHandler(t, ctx, "GET", "/healthz")
if !ctx.Router().IsWhitelisted("/api/health") {
t.Fatal("GET /api/health is not whitelisted")
}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/health", nil)
healthHandler(c)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)
}
var body struct {
ErrorMsg string `json:"error_msg"`
Data any `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.ErrorMsg != "" {
t.Fatalf("error_msg = %q, want empty", body.ErrorMsg)
}
if body.Data != nil {
t.Fatalf("data = %#v, want null", body.Data)
}
}
func TestHealthzRouteUnchanged(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx := core.NewContext(context.Background())
if err := New().Apply(ctx); err != nil {
t.Fatal(err)
}
handler := routeHandler(t, ctx, "GET", "/healthz")
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/healthz", nil)
handler(c)
var body map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["status"] != "ok" {
t.Fatalf("body = %s, want {status: ok}", w.Body.String())
}
}
func routeHandler(t *testing.T, ctx *core.Context, method, path string) gin.HandlerFunc {
t.Helper()
for _, rd := range ctx.Router().Routes() {
if rd.Method != method || rd.Path != path {
continue
}
if len(rd.Handlers) == 0 {
t.Fatalf("%s %s has no handlers", method, path)
}
switch h := rd.Handlers[0].(type) {
case gin.HandlerFunc:
return h
case func(*gin.Context):
return h
default:
t.Fatalf("unexpected handler type %T", rd.Handlers[0])
}
}
t.Fatalf("%s %s missing", method, path)
return nil
}
+14
View File
@@ -56,9 +56,23 @@ func (p *Plugin) Apply(ctx *core.Context) error {
ctx.Router().GET("/api/healthz", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
ctx.Router().GET("/api/health", func(c *gin.Context) {
c.JSON(http.StatusOK, response.OKNil())
})
ctx.Router().RegisterWhitelist("/api/health")
// 2. Public config
ctx.Router().GET("/api/v1/config/public", func(c *gin.Context) {
if p, err := core.Inject[contracts.PublicConfigProvider](ctx); err == nil && p != nil {
data, err := p.PublicConfig(c.Request.Context())
if err != nil {
logger.ErrorF(c.Request.Context(), "[System] public config provider failed: %v", err)
response.AbortInternal(c, "public config unavailable")
return
}
c.JSON(http.StatusOK, response.OK(data))
return
}
configs, err := listPublicSystemConfigs(c.Request.Context(), ctx)
if err != nil {
logger.ErrorF(c.Request.Context(), "[System] query public system configs failed: %v", err)
@@ -0,0 +1,149 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package system
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"Wavelet/core"
"Wavelet/core/contracts"
"github.com/gin-gonic/gin"
)
type stubPublic struct{ payload any }
func (s stubPublic) PublicConfig(context.Context) (any, error) { return s.payload, nil }
type errPublic struct{ err error }
func (s errPublic) PublicConfig(context.Context) (any, error) { return nil, s.err }
func TestPublicConfigUsesProviderWhenPresent(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx := core.NewContext(context.Background())
core.Provide[contracts.PublicConfigProvider](ctx, stubPublic{payload: map[string]string{"k": "v"}})
if err := New().Apply(ctx); err != nil {
t.Fatal(err)
}
body := invokePublicConfig(t, publicConfigHandler(t, ctx))
assertFlatKV(t, body)
}
func TestPublicConfigUsesProviderRegisteredAfterApply(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx := core.NewContext(context.Background())
if err := New().Apply(ctx); err != nil {
t.Fatal(err)
}
core.Provide[contracts.PublicConfigProvider](ctx, stubPublic{payload: map[string]string{"k": "v"}})
body := invokePublicConfig(t, publicConfigHandler(t, ctx))
assertFlatKV(t, body)
}
func TestPublicConfigDefaultWithoutProvider(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx := core.NewContext(context.Background())
if err := New().Apply(ctx); err != nil {
t.Fatal(err)
}
raw := invokePublicConfig(t, publicConfigHandler(t, ctx))
var data map[string]any
if err := json.Unmarshal(raw, &data); err != nil {
t.Fatal(err)
}
if _, ok := data["configs"]; !ok {
t.Fatalf("data = %s, want key configs", raw)
}
if _, ok := data["app"]; !ok {
t.Fatalf("data = %s, want key app", raw)
}
}
func TestPublicConfigProviderErrorAbortsInternal(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx := core.NewContext(context.Background())
core.Provide[contracts.PublicConfigProvider](ctx, errPublic{err: errors.New("secret boom")})
if err := New().Apply(ctx); err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/config/public", nil)
publicConfigHandler(t, ctx)(c)
if !c.IsAborted() {
t.Fatal("want request aborted on provider error")
}
if len(c.Errors) == 0 {
t.Fatal("want gin error on provider failure")
}
if got := c.Errors.Last().Error(); got != "public config unavailable" {
t.Fatalf("error = %q, want generic message", got)
}
if strings.Contains(w.Body.String(), "secret boom") {
t.Fatalf("leaked provider error: %s", w.Body.String())
}
}
func publicConfigHandler(t *testing.T, ctx *core.Context) gin.HandlerFunc {
t.Helper()
for _, rd := range ctx.Router().Routes() {
if rd.Method != "GET" || rd.Path != "/api/v1/config/public" {
continue
}
if len(rd.Handlers) == 0 {
break
}
switch h := rd.Handlers[0].(type) {
case gin.HandlerFunc:
return h
case func(*gin.Context):
return h
default:
t.Fatalf("unexpected handler type %T", rd.Handlers[0])
}
}
t.Fatal("public config route missing")
return nil
}
func invokePublicConfig(t *testing.T, handler gin.HandlerFunc) json.RawMessage {
t.Helper()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/config/public", nil)
handler(c)
var body struct {
Data json.RawMessage `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
return body.Data
}
func assertFlatKV(t *testing.T, raw json.RawMessage) {
t.Helper()
var data map[string]any
if err := json.Unmarshal(raw, &data); err != nil {
t.Fatal(err)
}
if data["k"] != "v" {
t.Fatalf("data = %s, want flat map", raw)
}
if _, ok := data["configs"]; ok {
t.Fatalf("data = %s, want provider payload without default configs", raw)
}
if _, ok := data["app"]; ok {
t.Fatalf("data = %s, want provider payload without default app", raw)
}
}
+4
View File
@@ -126,6 +126,10 @@ func (p *Plugin) Apply(ctx *core.Context) error {
uploadGroup.GET("", handler.ListFiles)
uploadGroup.DELETE("/:id", handler.DeleteFile)
uploadGroup.POST("/batch-download", handler.BatchDownloadFiles)
uploadGroup.GET("/my", handler.ListMyFiles)
uploadGroup.PUT("/:id", handler.UpdateMyFile)
uploadGroup.GET("/download/:id", handler.DownloadFile)
uploadGroup.POST("/download/batch", handler.BatchDownloadFiles)
}
adminUploadGroup := ctx.Router().Group("/api/v1/admin/uploads", loginMW)
@@ -0,0 +1,53 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package upload
import (
"context"
"testing"
"github.com/gin-gonic/gin"
"Wavelet/core"
"Wavelet/core/contracts"
)
type stubDBService struct{ contracts.DBService }
type stubStorageService struct{ contracts.StorageService }
type stubAuthService struct{ contracts.AuthService }
func (stubAuthService) RequireAuthMiddleware() any {
return gin.HandlerFunc(func(c *gin.Context) { c.Next() })
}
func TestUserUploadRoutes(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx := core.NewContext(context.Background())
core.Provide[contracts.DBService](ctx, stubDBService{})
core.Provide[contracts.StorageService](ctx, stubStorageService{})
core.Provide[contracts.AuthService](ctx, stubAuthService{})
if err := New().Apply(ctx); err != nil {
t.Fatal(err)
}
want := []string{
"GET /api/v1/upload/my",
"PUT /api/v1/upload/:id",
"GET /api/v1/upload/download/:id",
"POST /api/v1/upload/download/batch",
"GET /api/v1/upload",
"POST /api/v1/upload/batch-download",
}
found := make(map[string]bool, len(want))
for _, rd := range ctx.Router().Routes() {
found[rd.Method+" "+rd.Path] = true
}
for _, key := range want {
if !found[key] {
t.Errorf("missing route %s", key)
}
}
}
+16
View File
@@ -200,6 +200,22 @@ func ChangePassword(c *gin.Context) {
c.JSON(http.StatusOK, response.OKNil())
}
// Self returns the current authenticated user.
func Self(c *gin.Context) {
svc := getAuthService()
if svc == nil {
response.AbortUnauthorized(c, errUserNotFound)
return
}
user, err := svc.GetCurrentUser(c)
if err != nil {
logger.ErrorF(c.Request.Context(), "get current user failed: %v", err)
response.AbortUnauthorized(c, errUserNotFound)
return
}
c.JSON(http.StatusOK, response.OK(user))
}
// UpdateProfile updates profile info.
func UpdateProfile(c *gin.Context) {
var req updateProfileRequest
+18 -3
View File
@@ -120,14 +120,29 @@ func (p *Plugin) Apply(ctx *core.Context) error {
}
core.Provide[contracts.UserService](ctx, p.userSvc)
passThrough := gin.HandlerFunc(func(c *gin.Context) { c.Next() })
loginCap, registerCap, emailCap := passThrough, passThrough, passThrough
if capSvc, err := core.Inject[contracts.CaptchaService](ctx); err == nil && capSvc != nil {
if mw, ok := capSvc.VerifyMiddleware("login").(gin.HandlerFunc); ok {
loginCap = mw
}
if mw, ok := capSvc.VerifyMiddleware("register").(gin.HandlerFunc); ok {
registerCap = mw
}
if mw, ok := capSvc.VerifyMiddleware("send_email_code").(gin.HandlerFunc); ok {
emailCap = mw
}
}
// 3. Register HTTP Routes
userGroup := ctx.Router().Group("/api/v1/user")
{
userGroup.POST("/login", Login)
userGroup.POST("/register", Register)
userGroup.POST("/login", loginCap, Login)
userGroup.POST("/register", registerCap, Register)
userGroup.GET("/logout", Logout)
userGroup.POST("/send-email-code", SendEmailCode)
userGroup.POST("/send-email-code", emailCap, SendEmailCode)
userGroup.POST("/change-password", loginMW, ChangePassword)
userGroup.GET("/self", loginMW, Self)
userGroup.PUT("/profile", loginMW, UpdateProfile)
// Access Tokens
@@ -0,0 +1,74 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package user_test
import (
"context"
"reflect"
"testing"
"github.com/gin-gonic/gin"
"Wavelet/core"
"Wavelet/core/contracts"
"Wavelet/plugins/domain/user"
)
func TestApplyWithoutCaptchaServiceKeepsAuthRoutes(t *testing.T) {
ctx := core.NewContext(context.Background())
if err := user.New().Apply(ctx); err != nil {
t.Fatal(err)
}
want := map[string]bool{
"POST /api/v1/user/login": false,
"POST /api/v1/user/register": false,
"POST /api/v1/user/send-email-code": false,
}
for _, rd := range ctx.Router().Routes() {
key := rd.Method + " " + rd.Path
if _, ok := want[key]; ok {
want[key] = true
}
}
for key, ok := range want {
if !ok {
t.Errorf("missing route %s", key)
}
}
}
func TestInjectDoesNotRequireCaptchaService(t *testing.T) {
for _, dep := range user.New().Inject() {
if dep == reflect.TypeFor[contracts.CaptchaService]() {
t.Fatal("CaptchaService must not be a hard Inject() dependency")
}
}
}
type fakeCaptchaService struct{}
func (fakeCaptchaService) VerifyMiddleware(scope string) any {
return gin.HandlerFunc(func(c *gin.Context) { c.Next() })
}
func (fakeCaptchaService) ChallengeHandler() any { return gin.HandlerFunc(func(c *gin.Context) {}) }
func (fakeCaptchaService) RedeemHandler() any { return gin.HandlerFunc(func(c *gin.Context) {}) }
func TestApplyWithCaptchaServiceWrapsLogin(t *testing.T) {
ctx := core.NewContext(context.Background())
core.Provide[contracts.CaptchaService](ctx, fakeCaptchaService{})
if err := user.New().Apply(ctx); err != nil {
t.Fatal(err)
}
for _, rd := range ctx.Router().Routes() {
if rd.Method == "POST" && rd.Path == "/api/v1/user/login" {
if len(rd.Handlers) <= 1 {
t.Fatalf("login handler chain length = %d, want > 1", len(rd.Handlers))
}
return
}
}
t.Fatal("missing POST /api/v1/user/login")
}
@@ -0,0 +1,45 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package user_test
import (
"context"
"testing"
"Wavelet/core"
"Wavelet/core/extpoints"
"Wavelet/plugins/domain/user"
)
func TestSelfRouteRegisteredWithLoginProtection(t *testing.T) {
ctx := core.NewContext(context.Background())
if err := user.New().Apply(ctx); err != nil {
t.Fatal(err)
}
routes := ctx.Router().Routes()
self, ok := findRoute(routes, "GET", "/api/v1/user/self")
if !ok {
t.Fatal("GET /api/v1/user/self missing")
}
profile, ok := findRoute(routes, "PUT", "/api/v1/user/profile")
if !ok {
t.Fatal("PUT /api/v1/user/profile missing")
}
selfCount := len(self.Handlers) + len(self.Middlewares)
profileCount := len(profile.Handlers) + len(profile.Middlewares)
if selfCount < profileCount {
t.Fatalf("GET /api/v1/user/self handler/middleware count = %d, want >= %d (profile)", selfCount, profileCount)
}
}
func findRoute(routes []extpoints.RouteDefinition, method, path string) (extpoints.RouteDefinition, bool) {
for _, rd := range routes {
if rd.Method == method && rd.Path == path {
return rd, true
}
}
return extpoints.RouteDefinition{}, false
}
@@ -15,6 +15,7 @@ type httpAppConfig struct {
SessionAge int `config:"session_age" env:"APP_SESSION_AGE" default:"86400"`
SessionHTTPOnly bool `config:"session_http_only" env:"APP_SESSION_HTTP_ONLY" default:"true"`
SessionSecure bool `config:"session_secure" env:"APP_SESSION_SECURE"`
RedirectTrailingSlash *bool `config:"redirect_trailing_slash" env:"APP_REDIRECT_TRAILING_SLASH"`
}
type httpRedisConfig struct {
@@ -31,6 +31,11 @@ func BuildEngineWithConfig(appCfg httpAppConfig, redisCfg httpRedisConfig) (*gin
// 初始化路由
r := gin.New()
redirect := true
if appCfg.RedirectTrailingSlash != nil {
redirect = *appCfg.RedirectTrailingSlash
}
r.RedirectTrailingSlash = redirect
r.Use(gin.Recovery())
r.Use(corsMiddleware())
@@ -0,0 +1,113 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package driver_http
import (
"testing"
"Wavelet/core/extpoints"
)
func TestBuildEngineDefaultRedirectsTrailingSlash(t *testing.T) {
eng, err := BuildEngineWithConfig(httpAppConfig{}, httpRedisConfig{})
if err != nil {
t.Fatal(err)
}
if !eng.RedirectTrailingSlash {
t.Fatal("default RedirectTrailingSlash must be true")
}
}
func TestBuildEngineCanDisableRedirectTrailingSlash(t *testing.T) {
eng, err := BuildEngineWithConfig(httpAppConfig{RedirectTrailingSlash: boolPtr(false)}, httpRedisConfig{})
if err != nil {
t.Fatal(err)
}
if eng.RedirectTrailingSlash {
t.Fatal("RedirectTrailingSlash must honor false")
}
}
func TestBindAppConfigDefaultKeepsTrailingSlashRedirect(t *testing.T) {
cfg := bindAppConfig(t, map[string]any{}, map[string]string{})
if cfg.RedirectTrailingSlash != nil {
t.Fatal("absent redirect_trailing_slash must leave *bool nil")
}
eng, err := BuildEngineWithConfig(cfg, httpRedisConfig{})
if err != nil {
t.Fatal(err)
}
if !eng.RedirectTrailingSlash {
t.Fatal("default RedirectTrailingSlash must be true after Bind")
}
}
func TestBindAppConfigCanDisableTrailingSlashRedirect(t *testing.T) {
cfg := bindAppConfig(t, map[string]any{"app.redirect_trailing_slash": false}, nil)
if cfg.RedirectTrailingSlash == nil || *cfg.RedirectTrailingSlash {
t.Fatal("yaml false must bind *false")
}
eng, err := BuildEngineWithConfig(cfg, httpRedisConfig{})
if err != nil {
t.Fatal(err)
}
if eng.RedirectTrailingSlash {
t.Fatal("RedirectTrailingSlash must honor bound false")
}
}
func TestBindAppConfigEnvCanDisableTrailingSlashRedirect(t *testing.T) {
cfg := bindAppConfig(t, nil, map[string]string{"APP_REDIRECT_TRAILING_SLASH": "false"})
if cfg.RedirectTrailingSlash == nil || *cfg.RedirectTrailingSlash {
t.Fatal("env false must bind *false")
}
eng, err := BuildEngineWithConfig(cfg, httpRedisConfig{})
if err != nil {
t.Fatal(err)
}
if eng.RedirectTrailingSlash {
t.Fatal("RedirectTrailingSlash must honor env-bound false")
}
}
type slashConfigSource struct {
values map[string]any
env map[string]string
}
func (s slashConfigSource) Lookup(path string) (any, bool) {
v, ok := s.values[path]
return v, ok
}
func (s slashConfigSource) LookupEnv(name string) (string, bool) {
v, ok := s.env[name]
return v, ok
}
func (s slashConfigSource) Describe() string { return "slash-test" }
func bindAppConfig(t *testing.T, values map[string]any, env map[string]string) httpAppConfig {
t.Helper()
if values == nil {
values = map[string]any{}
}
if env == nil {
env = map[string]string{}
}
r := extpoints.NewConfigRegistry(slashConfigSource{values: values, env: env})
if err := r.Declare("driver_http", extpoints.ConfigBinding{Prefix: "app", Target: &httpAppConfig{}}); err != nil {
t.Fatal(err)
}
if err := r.Resolve(); err != nil {
t.Fatal(err)
}
var cfg httpAppConfig
if err := r.Bind("app", &cfg); err != nil {
t.Fatal(err)
}
return cfg
}
func boolPtr(v bool) *bool { return &v }