From ae29884231496fed12ed3fc24c1ec7144bce47dc Mon Sep 17 00:00:00 2001 From: Dmitri Aleksandrov Date: Mon, 19 Oct 2026 13:14:27 +0300 Subject: [PATCH] feat(translator): look the translations up in a chain of sources translator.Source translates a key in one language or reports that it has none; WithSources looks every language of a request up in the sources in order, so your messages go before the built-in ones and the built-in ones translate the rest. Embedded is the source of the YAML locales of valigo. The named parameters of the messages, {"max": 64}, reach the sources for the named placeholders of go-i18n and others: the helper of the validator passes them, the interfaces are unchanged. --- internal/helper/helper.go | 14 ++++++++ internal/helper/helper_test.go | 20 +++++++++++ shared/message.go | 13 ++++++- shared/message_test.go | 15 ++++++++ translator/inmem.go | 28 +++++++++------ translator/source.go | 65 ++++++++++++++++++++++++++++++++++ translator/source_test.go | 57 +++++++++++++++++++++++++++++ translator/translator.go | 8 +++++ 8 files changed, 209 insertions(+), 11 deletions(-) create mode 100644 translator/source.go create mode 100644 translator/source_test.go diff --git a/internal/helper/helper.go b/internal/helper/helper.go index 05dbd2a..581c920 100644 --- a/internal/helper/helper.go +++ b/internal/helper/helper.go @@ -31,6 +31,20 @@ func (h *Helper) ErrorT(ctx context.Context, field fmap.Field, value any, locale } } +// paramsTranslator is a translator that passes the named parameters to its sources, the translator of valigo is. +type paramsTranslator interface { + TParams(ctx context.Context, key string, args []any, params map[string]any) string +} + +// ErrorParams is ErrorT with the named parameters of the message for the sources of the translator. +func (h *Helper) ErrorParams(ctx context.Context, field fmap.Field, value any, localeKey string, args []any, params map[string]any) shared.Error { + pt, ok := h.Translator.(paramsTranslator) + if !ok { + return h.ErrorT(ctx, field, value, localeKey, args...) + } + return shared.Error{Location: h.Location(field), Message: pt.TParams(ctx, localeKey, args, params), Value: value, Code: localeKey} +} + // FieldLocation returns the location of the field in errors. func (h *Helper) FieldLocation(field fmap.Field) string { return h.Location(field) diff --git a/internal/helper/helper_test.go b/internal/helper/helper_test.go index 9d72378..44f45ea 100644 --- a/internal/helper/helper_test.go +++ b/internal/helper/helper_test.go @@ -36,3 +36,23 @@ func TestHelperFieldLocation(t *testing.T) { t.Errorf("FieldLocation() = %q, want Name", got) } } + +// plainTranslator is a translator without the named parameters. +type plainTranslator struct{} + +func (plainTranslator) ErrorT(_ context.Context, format string, _ ...any) error { return nil } +func (plainTranslator) T(_ context.Context, format string, _ ...any) string { return "plain " + format } + +func TestHelperErrorParams(t *testing.T) { + strg, _ := fmap.GetFrom(admin{}) + field := strg.MustFind("Name") + h := New() + err := h.ErrorParams(context.Background(), field, "v", "validation:string:Cannot be longer than %d characters", []any{3}, map[string]any{"max": 3}) + if err.Message != "Cannot be longer than 3 characters" || err.Location != "Name" || err.Code != "validation:string:Cannot be longer than %d characters" { + t.Errorf("ErrorParams: %+v", err) + } + h.Translator = plainTranslator{} + if err := h.ErrorParams(context.Background(), field, "v", "k", nil, nil); err.Message != "plain k" { + t.Errorf("ErrorParams of a translator without the parameters: %+v", err) + } +} diff --git a/shared/message.go b/shared/message.go index 3e83b80..27db20c 100644 --- a/shared/message.go +++ b/shared/message.go @@ -54,12 +54,23 @@ func (m Msg) with(name string, value any) Msg { } // Error builds the error of the field with the translated message, the code and the parameters of m. +// The helper of the validator passes the named parameters to the translator, for the sources with named placeholders. func (m Msg) Error(ctx context.Context, h Helper, field fmap.Field, value any) Error { - err := h.ErrorT(ctx, field, value, m.Key, m.Args...) + var err Error + if ph, ok := h.(paramsHelper); ok { + err = ph.ErrorParams(ctx, field, value, m.Key, m.Args, m.Params) + } else { + err = h.ErrorT(ctx, field, value, m.Key, m.Args...) + } err.Code, err.Params = m.Code, m.Params return err } +// paramsHelper is a Helper that passes the named parameters of the messages to the translator. +type paramsHelper interface { + ErrorParams(ctx context.Context, field fmap.Field, value any, key string, args []any, params map[string]any) Error +} + // key returns the message of a rule configured by a locale key, its code is the key. func key(localeKey string, args []any) Msg { return Msg{Code: localeKey, Key: localeKey, Args: args} diff --git a/shared/message_test.go b/shared/message_test.go index 93eb5b2..7c700f6 100644 --- a/shared/message_test.go +++ b/shared/message_test.go @@ -2,8 +2,11 @@ package shared import ( "context" + "fmt" "testing" + "github.com/insei/fmap/v3" + "github.com/stretchr/testify/assert" ) @@ -117,3 +120,15 @@ func TestMapMessages(t *testing.T) { newLabels(&required).Required() assert.Equal(t, []Error{{Location: "Labels", Message: "validation:map:Should be fulfilled", Code: "map.required"}}, required.validateFull(&mapsSample{})) } + +// paramsPathHelper is pathHelper that builds the messages of the named parameters. +type paramsPathHelper struct{ pathHelper } + +func (paramsPathHelper) ErrorParams(_ context.Context, field fmap.Field, value any, key string, _ []any, params map[string]any) Error { + return Error{Location: field.GetStructPath(), Message: fmt.Sprint(key, params), Value: value} +} + +func TestMsgErrorParams(t *testing.T) { + err := M("string.max_len", "max", P("max", 3)).Error(context.Background(), paramsPathHelper{}, sampleField(t, "Text"), "abcd") + assert.Equal(t, Error{Location: "Text", Message: "maxmap[max:3]", Value: "abcd", Code: "string.max_len", Params: map[string]any{"max": 3}}, err) +} diff --git a/translator/inmem.go b/translator/inmem.go index 8e79ff4..d9d9f0b 100644 --- a/translator/inmem.go +++ b/translator/inmem.go @@ -1,7 +1,6 @@ package translator import ( - "fmt" "io/fs" "strings" ) @@ -85,18 +84,27 @@ func (t *inMemTranslatorStorage) Merge(locales map[string]map[string]string) { // Get returns the translated value for a given format and language preferences. // A format with plural forms (format#one, format#few, format#many, format#other) is translated // by the plural category of the first integer argument in the language. -func (t *inMemTranslatorStorage) Get(prefer []string, format string, args ...any) string { - translatedFormat := format - for _, preferLang := range prefer { - if langFormat, ok := t.translate(preferLang, format, args); ok { - translatedFormat = langFormat - break +func (t *inMemTranslatorStorage) Get(prefer []string, key string, args ...any) string { + return t.getParams(prefer, key, args, nil) +} + +// getParams is Get, the storage has no named placeholders. +func (t *inMemTranslatorStorage) getParams(prefer []string, key string, args []any, _ map[string]any) string { + for _, lang := range prefer { + if msg, ok := t.Translate(lang, key, args, nil); ok { + return msg } } - if len(args) == 0 && strings.IndexByte(translatedFormat, '%') < 0 { - return translatedFormat + return format(key, args) +} + +// Translate returns the translation of the key in the language, see Source. +func (t *inMemTranslatorStorage) Translate(lang, key string, args []any, _ map[string]any) (string, bool) { + langFormat, ok := t.translate(lang, key, args) + if !ok { + return "", false } - return fmt.Sprintf(translatedFormat, args...) + return format(langFormat, args), true } // translate returns the translation of format in lang, the plural form if the format has plural forms. diff --git a/translator/source.go b/translator/source.go new file mode 100644 index 0000000..38b30c1 --- /dev/null +++ b/translator/source.go @@ -0,0 +1,65 @@ +package translator + +import ( + "fmt" + "strings" +) + +// Source is a source of the translations of the messages: the YAML locales of valigo, a bundle of go-i18n... +// A translator looks the languages of a request up in its sources in order, see WithSources. +type Source interface { + // Translate returns the message of the key in the language formatted with the arguments, false if the source + // has no translation of the key in the language. args are the format arguments of the key, params are the same + // values by their names, e.g. {"max": 64}, for the sources with named placeholders; params can be nil. + Translate(lang, key string, args []any, params map[string]any) (string, bool) +} + +// WithSources returns an option that looks the translations up in the sources: for every language of a request +// in order, the first source with a translation of the key wins. Your messages go before the built-in ones, +// the built-in ones translate the rest: +// +// translator.New(translator.WithSources(goi18n.Source(bundle), translator.Embedded())) +// +// A key without a translation in any language is the message itself. +func WithSources(sources ...Source) Option { + return &storageOption{storage: &sourcesStorage{sources: sources}} +} + +// Embedded returns the source of the built-in YAML locales of valigo, the options add your translations to them. +func Embedded(opts ...InMemStorageOption) Source { + return newInMemStorage(EmbedFSLocalesYAML, opts...).(*inMemTranslatorStorage) +} + +// paramsStorage is a storage that passes the named parameters of the messages to its sources. +type paramsStorage interface { + getParams(prefer []string, key string, args []any, params map[string]any) string +} + +// sourcesStorage is the storage of the translations of the sources, see WithSources. +type sourcesStorage struct { + sources []Source +} + +// Get returns the translation of the key in the first of the preferred languages that has one. +func (s *sourcesStorage) Get(prefer []string, key string, args ...any) string { + return s.getParams(prefer, key, args, nil) +} + +func (s *sourcesStorage) getParams(prefer []string, key string, args []any, params map[string]any) string { + for _, lang := range prefer { + for _, source := range s.sources { + if msg, ok := source.Translate(lang, key, args, params); ok { + return msg + } + } + } + return format(key, args) +} + +// format formats the message with the arguments, a message without arguments and verbs is returned as is. +func format(msg string, args []any) string { + if len(args) == 0 && strings.IndexByte(msg, '%') < 0 { + return msg + } + return fmt.Sprintf(msg, args...) +} diff --git a/translator/source_test.go b/translator/source_test.go new file mode 100644 index 0000000..61c18e1 --- /dev/null +++ b/translator/source_test.go @@ -0,0 +1,57 @@ +package translator + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" +) + +// mapSource translates the keys of its languages and keeps the parameters of the last translation. +type mapSource struct { + messages map[string]map[string]string + params map[string]any +} + +func (s *mapSource) Translate(lang, key string, args []any, params map[string]any) (string, bool) { + msg, ok := s.messages[lang][key] + if ok { + s.params = params + } + return format(msg, args), ok +} + +func TestWithSources(t *testing.T) { + own := &mapSource{messages: map[string]map[string]string{ + "ru": {"validation:string:Should be email address": "Нужен e-mail"}, + "en": {"validation:string:Should be URL": "A link, please", "greeting %s": "Hello, %s"}, + }} + tr := New(WithSources(own, Embedded())) + ru := ContextWithLanguages(context.Background(), "ru") + assert.Equal(t, "Нужен e-mail", tr.T(ru, "validation:string:Should be email address"), "the first source") + assert.Equal(t, "Должно быть URL", tr.T(ru, "validation:string:Should be URL"), + "the built-in source of the language before the first source of the default language") + assert.Equal(t, "Hello, Ann", tr.T(context.Background(), "greeting %s", "Ann")) + assert.Equal(t, "no translation 1", tr.T(ru, "no translation %d", 1), "the key itself") + assert.Equal(t, "plain", tr.T(ru, "plain")) + assert.EqualError(t, tr.ErrorT(ru, "validation:string:Should be email address"), "Нужен e-mail") + + pt := tr.(*translator) + params := map[string]any{"max": 3} + assert.Equal(t, "Нужен e-mail", pt.TParams(ru, "validation:string:Should be email address", nil, params)) + assert.Equal(t, params, own.params, "the parameters reach the source") +} + +// plainStorage is a storage without the parameters. +type plainStorage struct{} + +func (plainStorage) Get(_ []string, key string, _ ...any) string { return "plain " + key } + +func TestTParamsOfStorages(t *testing.T) { + assert.Equal(t, "plain k", New(WithStorage(plainStorage{})).(*translator).TParams(context.Background(), "k", nil, nil)) + builtin := New().(*translator) + assert.Equal(t, "Should be URL", builtin.TParams(context.Background(), "validation:string:Should be URL", nil, map[string]any{"x": 1})) + assert.Equal(t, "Should be URL", NewInMemStorage().Get([]string{"en"}, "validation:string:Should be URL")) + _, ok := Embedded().Translate("xx", "validation:string:Should be URL", nil, nil) + assert.False(t, ok) +} diff --git a/translator/translator.go b/translator/translator.go index d34adce..ccb7d30 100644 --- a/translator/translator.go +++ b/translator/translator.go @@ -39,6 +39,14 @@ func (t *translator) T(ctx context.Context, format string, args ...any) string { return t.storage.Get(t.getLanguages(ctx), format, args...) } +// TParams returns the translated message, the named parameters are passed to the sources, see Source. +func (t *translator) TParams(ctx context.Context, key string, args []any, params map[string]any) string { + if s, ok := t.storage.(paramsStorage); ok { + return s.getParams(t.getLanguages(ctx), key, args, params) + } + return t.storage.Get(t.getLanguages(ctx), key, args...) +} + // New returns a new Translator instance with default settings. func New(opts ...Option) Translator { t := &translator{