fix(service): copy handler slices in options

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Virgil 2026-04-02 07:10:49 +00:00
parent d95218917e
commit f091340da3
2 changed files with 27 additions and 1 deletions

View file

@ -55,7 +55,9 @@ func WithLocation(location string) Option {
// WithHandlers sets custom handlers (replaces default handlers).
func WithHandlers(handlers ...KeyHandler) Option {
return func(s *Service) { s.handlers = handlers }
return func(s *Service) {
s.handlers = append([]KeyHandler(nil), handlers...)
}
}
// WithDefaultHandlers adds the default i18n.* namespace handlers.

View file

@ -33,6 +33,16 @@ func (h serviceMutatingHandler) Handle(key string, args []any, next func() strin
return "mutated"
}
type serviceStubHandler struct{}
func (serviceStubHandler) Match(key string) bool {
return key == "custom.stub"
}
func (serviceStubHandler) Handle(key string, args []any, next func() string) string {
return "stub"
}
type underscoreLangLoader struct{}
func (underscoreLangLoader) Languages() []string {
@ -137,6 +147,20 @@ func TestServiceTranslateMissingKey(t *testing.T) {
}
}
func TestNewWithHandlersCopiesInputSlice(t *testing.T) {
handlers := []KeyHandler{serviceStubHandler{}}
svc, err := New(WithHandlers(handlers...))
if err != nil {
t.Fatalf("New() failed: %v", err)
}
handlers[0] = LabelHandler{}
if got := svc.T("custom.stub"); got != "stub" {
t.Fatalf("T(custom.stub) = %q, want %q", got, "stub")
}
}
func TestServiceTDirectKeys(t *testing.T) {
svc, err := New()
if err != nil {