diff --git a/context.go b/context.go index e2902dc..d791855 100644 --- a/context.go +++ b/context.go @@ -155,6 +155,17 @@ func (ctx *Context) WithData(key string, value any) *Context { return clone } +// WithIdentity returns a cloned context with a different identity value. +// Example: next := ctx.WithIdentity("user-123"). +func (ctx *Context) WithIdentity(identity string) *Context { + clone := ctx.Clone() + if clone == nil { + return nil + } + clone.SetIdentity(identity) + return clone +} + // SetLocale updates the context locale and reapplies it to the active // translator. // Example: ctx.SetLocale("en-US"). diff --git a/context_test.go b/context_test.go index a8776b9..793ca50 100644 --- a/context_test.go +++ b/context_test.go @@ -181,6 +181,27 @@ func TestContext_WithDataReturnsClonedContext(t *testing.T) { } } +func TestContext_WithIdentityReturnsClonedContext(t *testing.T) { + ctx := NewContext() + ctx.SetIdentity("user-001") + ctx.SetData("theme", "dark") + + next := ctx.WithIdentity("user-123") + + if next == ctx { + t.Fatal("WithIdentity should return a cloned context") + } + if got := ctx.Identity; got != "user-001" { + t.Fatalf("WithIdentity should not mutate the original context, got %q", got) + } + if got := next.Identity; got != "user-123" { + t.Fatalf("WithIdentity should set the requested identity on the clone, got %q", got) + } + if got := next.Data["theme"]; got != "dark" { + t.Fatalf("WithIdentity should preserve existing data on the clone, got %v", got) + } +} + func TestContext_Setters_NilReceiver(t *testing.T) { var ctx *Context