Skip to content

Commit

Permalink
Add convenience function MustLocalizeMessage (#352)
Browse files Browse the repository at this point in the history
Added a must variant of `LocalizeMessage` (like `Localize` &
`MustLocalize`)
  • Loading branch information
apricotbucket28 authored Jan 12, 2025
1 parent d096e3f commit 711fb20
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
11 changes: 10 additions & 1 deletion i18n/localizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func (l *Localizer) Localize(lc *LocalizeConfig) (string, error) {
return msg, err
}

// Localize returns a localized message.
// LocalizeMessage returns a localized message.
func (l *Localizer) LocalizeMessage(msg *Message) (string, error) {
return l.Localize(&LocalizeConfig{
DefaultMessage: msg,
Expand Down Expand Up @@ -236,3 +236,12 @@ func (l *Localizer) MustLocalize(lc *LocalizeConfig) string {
}
return localized
}

// MustLocalizeMessage is similar to LocalizeMessage, except it panics if an error happens.
func (l *Localizer) MustLocalizeMessage(msg *Message) string {
localized, err := l.LocalizeMessage(msg)
if err != nil {
panic(err)
}
return localized
}
11 changes: 11 additions & 0 deletions i18n/localizer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -768,3 +768,14 @@ func TestMustLocalize(t *testing.T) {
MessageID: "hello",
})
}

func TestMustLocalizeMessage(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatalf("MustLocalizeMessage did not panic")
}
}()
bundle := NewBundle(language.English)
localizer := NewLocalizer(bundle)
localizer.MustLocalizeMessage(&Message{})
}

0 comments on commit 711fb20

Please sign in to comment.