Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ updates:
- "/integrations/huma"
- "/integrations/gin"
- "/integrations/echo"
- "/integrations/goi18n"
- "/bench"
- "/examples/*"
schedule:
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ and a conversion that doesn't fit the field doesn't compile:
# Errors and translations
* Every error has the translated message, the location (`Tags[1]`, `address.city` with JSON paths), the value, a stable `Code` and named `Params`
* Messages in English, German, Spanish, French and Russian with plural forms, the language of every request from the context, an `Accept-Language` middleware
* Translations from a chain of sources: your catalogs of [go-i18n](https://github.com/nicksnyder/go-i18n) by `github.com/insei/valigo/integrations/goi18n`, the built-in YAML for the rest, or your own source
* `problem`: the errors as `application/problem+json` of RFC 9457 with JSON pointers
* The rules as the keywords of JSON Schema, `vhuma.OpenAPI` puts them into the OpenAPI document of huma: the clients see `maxLength`, `format`, `enum` of the rules
* `github.com/insei/valigo/integrations/huma`, `github.com/insei/valigo/integrations/gin`, `github.com/insei/valigo/integrations/echo`: the rules of valigo in [huma](https://huma.rocks), [gin](https://gin-gonic.com) and [echo](https://echo.labstack.com)
Expand Down
66 changes: 66 additions & 0 deletions docs/features/goi18n.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# go-i18n

The module `github.com/insei/valigo/integrations/goi18n` translates the messages of valigo by a bundle of [go-i18n](https://github.com/nicksnyder/go-i18n), so the messages of the validation live in the catalogs of your service with the rest of its texts.

```bash
go get github.com/insei/valigo/integrations/goi18n@latest
```

- `goi18n.Source(bundle)` is a [source of translations](translations.md#sources-of-translations): `translator.WithSources(goi18n.Source(bundle), translator.Embedded())` takes your messages from the bundle and the built-in YAML locales translate the rest.
- The message IDs are the locale keys of valigo, `validation:string:Cannot be longer than %d characters`, see [`translator/locales`](https://github.com/Insei/valigo/tree/main/translator/locales).
- A message uses the named parameters of the rule, `{{.max}}`, `{{.min}}`, `{{.field}}` — the params of the [codes](errors.md#codes-for-clients) — or the format verbs of the key, `%d`. The plural forms are chosen by the first integer argument, `{{.PluralCount}}` is it.
- A language without the message in the bundle has no translation: the fallback of go-i18n to its default language isn't used, the next sources translate the language of the request.
- `goi18n.Messages(lang)` exports the built-in messages of a language with their plural forms, to add them to a bundle or to write them to the files of the translators.

## Example

```go
package main

import (
"context"
"fmt"

"github.com/insei/valigo"
"github.com/insei/valigo/integrations/goi18n"
"github.com/insei/valigo/rules/str"
"github.com/insei/valigo/translator"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)

type SignUp struct {
Name string
Email string
}

func main() {
bundle := i18n.NewBundle(language.English)
_ = bundle.AddMessages(language.Russian, &i18n.Message{
ID: "validation:string:Cannot be longer than %d characters",
One: "Имя — не больше {{.max}} буквы",
Few: "Имя — не больше {{.max}} букв",
Many: "Имя — не больше {{.max}} букв",
Other: "Имя — не больше {{.max}} буквы",
})

tr := translator.New(translator.WithSources(goi18n.Source(bundle), translator.Embedded()))
v := valigo.New(valigo.WithTranslator(tr))
valigo.Configure[SignUp](v, func(b valigo.Configurator[SignUp], s *SignUp) {
b.Field(&s.Name).As(str.Of).MaxRunes(3)
b.Field(&s.Email).As(str.Of).Email()
})

ctx := translator.ContextWithLanguages(context.Background(), "ru")
for _, err := range v.ValidateTyped(ctx, &SignUp{Name: "Анастасия", Email: "ann"}) {
fmt.Println(err.Location, "-", err.Message)
}
}
```

Output:

```text
Name - Имя — не больше 3 букв
Email - Должно быть электронным адресом
```
1 change: 1 addition & 0 deletions docs/features/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@ The separate modules for the frameworks.
| [JSON Schema](schema.md) | the rules as the keywords of JSON Schema for the generators of API schemas, `Constraints` |
| [huma](huma.md) | `github.com/insei/valigo/integrations/huma`: the rules in the `Resolve` of huma inputs with the locations of huma and in its OpenAPI document |
| [gin](gin.md) | `github.com/insei/valigo/integrations/gin`: the `binding.StructValidator` of gin and validation with the language of the request |
| [go-i18n](goi18n.md) | `github.com/insei/valigo/integrations/goi18n`: the messages from a bundle of go-i18n, the built-in ones for the rest |
| [echo](echo.md) | `github.com/insei/valigo/integrations/echo`: the `echo.Validator` and validation with the language of the request |
27 changes: 27 additions & 0 deletions docs/features/translations.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,30 @@ Output:
- `storage.Merge(locales)` adds the translations of several languages at once, e.g. from your own YAML files read by `translator.LocalesFromFS(fsys)`: `locales/<lang>/data.yaml` with the same nested format as the built-in locales.
- `translator.NewInMemStorage(translator.WithInMemData(data))` replaces the built-in locales with yours.
- [`str.WithRegexpLocaleKey`](strings.md#regexp-message) sets the key of a `Regexp` rule.

## Sources of translations

The translator looks the messages up in its sources: the built-in YAML locales by default, your catalogs of an i18n library, your own source. `translator.WithSources` chains them — for every language of a request in order, the first source with a translation of the key wins:

```go
tr := translator.New(translator.WithSources(goi18n.Source(bundle), translator.Embedded()))
v := valigo.New(valigo.WithTranslator(tr))
```

Your messages in go-i18n override the built-in ones, the built-in YAML translates the rest; a German request gets the built-in German before your English. `translator.Embedded(opts...)` is the built-in YAML locales as a source, with your additions by `WithInMemData`.

A source implements `translator.Source`:

```go
type Source interface {
Translate(lang, key string, args []any, params map[string]any) (string, bool)
}
```

`args` are the format arguments of the key, `params` are the same values by their names, `{"max": 64}`, for the libraries with named placeholders; `false` passes the language to the next source. The sources:

| Source | Module |
|---|---|
| the built-in YAML locales | `translator.Embedded()` |
| [go-i18n](goi18n.md) | `github.com/insei/valigo/integrations/goi18n` |

28 changes: 28 additions & 0 deletions integrations/goi18n/count_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package goi18n

import (
"testing"

"github.com/nicksnyder/go-i18n/v2/i18n"
)

func TestCount(t *testing.T) {
for _, arg := range []any{int(3), int8(3), int16(3), int32(3), int64(3), uint(3), uint8(3), uint16(3), uint32(3), uint64(3)} {
if n, ok := count([]any{"x", arg}); !ok || n != 3 {
t.Errorf("count of %T: %d, %v", arg, n, ok)
}
}
if _, ok := count([]any{1.5, "x"}); ok {
t.Error("a float isn't a count")
}
}

func TestSetForm(t *testing.T) {
m := &i18n.Message{}
for _, c := range []string{"zero", "one", "two", "few", "many", "other"} {
setForm(m, c, c)
}
if *m != (i18n.Message{Zero: "zero", One: "one", Two: "two", Few: "few", Many: "many", Other: "other"}) {
t.Errorf("forms: %+v", m)
}
}
18 changes: 18 additions & 0 deletions integrations/goi18n/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module github.com/insei/valigo/integrations/goi18n

go 1.27

replace github.com/insei/valigo => ../../

require (
github.com/insei/valigo v0.0.0-00010101000000-000000000000
github.com/nicksnyder/go-i18n/v2 v2.6.1
github.com/stretchr/testify v1.12.1
golang.org/x/text v0.43.0
)

require (
github.com/insei/fmap/v3 v3.3.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
16 changes: 16 additions & 0 deletions integrations/goi18n/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/insei/fmap/v3 v3.3.0 h1:VdTwCpJxQWyjUqomfNDwRHkWA5XeHnb2UNHB7J2k8UA=
github.com/insei/fmap/v3 v3.3.0/go.mod h1:Kk0gs7nKb4E/JycKJFnrsX5hlyBBe0yetGKFCJG0vzk=
github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
153 changes: 153 additions & 0 deletions integrations/goi18n/goi18n.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// Package goi18n translates the messages of valigo by a bundle of go-i18n (github.com/nicksnyder/go-i18n/v2).
//
// Source is a source of translations of the translator of valigo, the built-in YAML locales translate the rest:
//
// tr := translator.New(translator.WithSources(goi18n.Source(bundle), translator.Embedded()))
// v := valigo.New(valigo.WithTranslator(tr))
//
// The message IDs are the locale keys of valigo, validation:string:Cannot be longer than %d characters.
// A message can use the named parameters of the rule, {{.max}}, or the format verbs of the key, %d;
// the plural forms are chosen by the first integer argument. Messages exports the built-in messages
// to translate them with your messages.
package goi18n

import (
"errors"
"fmt"
"slices"
"strings"
"sync"

"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"

"github.com/insei/valigo/translator"
)

// source is the translator.Source of a bundle.
type source struct {
bundle *i18n.Bundle
// localizers are the localizers of the languages, created once
localizers sync.Map
}

// Source returns the translator.Source of the messages of the bundle. A language without the message in the bundle
// has no translation, the fallback of go-i18n to the default language isn't used: the next sources translate it.
func Source(bundle *i18n.Bundle) translator.Source {
return &source{bundle: bundle}
}

type localizer struct {
l *i18n.Localizer
base language.Base
}

func (s *source) localizer(lang string) localizer {
if l, ok := s.localizers.Load(lang); ok {
return l.(localizer)
}
base, _ := language.Make(lang).Base()
l, _ := s.localizers.LoadOrStore(lang, localizer{l: i18n.NewLocalizer(s.bundle, lang), base: base})
return l.(localizer)
}

// Translate returns the message of the key in the language, see translator.Source.
func (s *source) Translate(lang, key string, args []any, params map[string]any) (string, bool) {
l := s.localizer(lang)
cfg := &i18n.LocalizeConfig{MessageID: key, TemplateData: params}
if n, ok := count(args); ok {
cfg.PluralCount = n
}
msg, tag, err := l.l.LocalizeWithTag(cfg)
if err != nil {
return "", false
}
if base, _ := tag.Base(); base != l.base {
// the fallback of go-i18n to another language
return "", false
}
if len(args) > 0 && strings.IndexByte(msg, '%') >= 0 {
msg = fmt.Sprintf(msg, args...)
}
return msg, true
}

// count returns the first integer argument, the count of the plural forms.
func count(args []any) (int64, bool) {
for _, arg := range args {
switch n := arg.(type) {
case int:
return int64(n), true
case int8:
return int64(n), true
case int16:
return int64(n), true
case int32:
return int64(n), true
case int64:
return n, true
case uint:
return int64(n), true
case uint8:
return int64(n), true
case uint16:
return int64(n), true
case uint32:
return int64(n), true
case uint64:
return int64(n), true
}
}
return 0, false
}

// Messages returns the built-in messages of valigo in the language as the messages of go-i18n, with their plural
// forms, e.g. to add them to a bundle or to write them to the files of the translators.
// The messages keep the format verbs of the keys, %d.
func Messages(lang string) ([]*i18n.Message, error) {
// the embedded locales are valid, the tests of the translator check them
locales, _ := translator.LocalesFromFS(translator.EmbedFSLocalesYAML)
translations, ok := locales[lang]
if !ok {
return nil, errors.New("goi18n: no built-in messages of " + lang)
}
byID := map[string]*i18n.Message{}
var ids []string
for key, value := range translations {
id, category, plural := strings.Cut(key, "#")
m, ok := byID[id]
if !ok {
m = &i18n.Message{ID: id}
byID[id] = m
ids = append(ids, id)
}
if !plural {
category = "other"
}
setForm(m, category, value)
}
slices.Sort(ids)
messages := make([]*i18n.Message, len(ids))
for i, id := range ids {
messages[i] = byID[id]
}
return messages, nil
}

// setForm sets the plural form of the CLDR category of the message, other for an unknown category.
func setForm(m *i18n.Message, category, value string) {
switch category {
case "zero":
m.Zero = value
case "one":
m.One = value
case "two":
m.Two = value
case "few":
m.Few = value
case "many":
m.Many = value
default:
m.Other = value
}
}
Loading
Loading