Skip to content

Update translator.go #31

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
25 changes: 20 additions & 5 deletions translator.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"fmt"
"strconv"
"strings"

"sync"
"github.com/go-playground/locales"
)

Expand Down Expand Up @@ -70,13 +70,28 @@ var _ Translator = new(translator)
var _ locales.Translator = new(translator)

type translator struct {
sync.RWMutex
locales.Translator
translations map[interface{}]*transText
cardinalTanslations map[interface{}][]*transText // array index is mapped to locales.PluralRule index + the locales.PluralRuleUnknown
ordinalTanslations map[interface{}][]*transText
rangeTanslations map[interface{}][]*transText
}

func (sn *translator) SetTranslations(key interface{}, val *transText) {
sn.Lock()
defer sn.Unlock()
sn.translations[key] = val
}
func (sn *translator) GetTranslations(key interface{}) (*transText, bool) {
sn.Lock()
defer sn.Unlock()
if val, ok := sn.translations[key]; ok {
return val, true
}
return nil, false
}

type transText struct {
text string
indexes []int
Expand All @@ -96,8 +111,8 @@ func newTranslator(trans locales.Translator) Translator {
// {#} is the only replacement type accepted and are ad infinitum
// eg. one: '{0} day left' other: '{0} days left'
func (t *translator) Add(key interface{}, text string, override bool) error {

if _, ok := t.translations[key]; ok && !override {
if _, ok := t.GetTranslations(key); ok && !override {
return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text}
}

Expand All @@ -124,8 +139,8 @@ func (t *translator) Add(key interface{}, text string, override bool) error {
trans.indexes = append(trans.indexes, idx)
trans.indexes = append(trans.indexes, idx+len(s))
}

t.translations[key] = trans
//fatal error: concurrent map read and map write
t.SetTranslations(key, trans)

return nil
}
Expand Down