Skip to content

Commit

Permalink
feat: Localized method with struct
Browse files Browse the repository at this point in the history
  • Loading branch information
SpectatorNan committed May 20, 2024
1 parent 350cc73 commit 1171869
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,18 @@ import "github.com/SpectatorNan/go-zero-i18n/goi18nx"



```

### Support From DB
```go
// Shop is a struct from db
func (s *Shop) Name(ctx context.Context) string {
langMap := map[language.Tag]string{
language.English: s.NameEn,
language.Chinese: s.NameCn,
// more language mapping
}
return goi18nx.LocalizedString(ctx, s.NameCn, langMap)
}

```
12 changes: 12 additions & 0 deletions goi18nx/goi18nx.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,15 @@ func FetchCurrentLanguageFromCtx(ctx context.Context) (*language.Tag, bool) {
}
return nil, false
}

func LocalizedString(ctx context.Context, defaultValue string, langMap map[language.Tag]string) string {
langTag, tagExists := FetchCurrentLanguageFromCtx(ctx)
if !tagExists {
return defaultValue
}
str, ok := langMap[*langTag]
if !ok {
return defaultValue
}
return str
}

0 comments on commit 1171869

Please sign in to comment.