diff --git a/service.go b/service.go index 5c5e78f..2cc88a5 100644 --- a/service.go +++ b/service.go @@ -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. diff --git a/service_test.go b/service_test.go index f6e393b..c36d2a5 100644 --- a/service_test.go +++ b/service_test.go @@ -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 {