From 711fb20ca0bb64b76548bee94f8076bdecb393d9 Mon Sep 17 00:00:00 2001 From: apricotbucket28 <71973804+apricotbucket28@users.noreply.github.com> Date: Sun, 12 Jan 2025 16:07:59 -0300 Subject: [PATCH] Add convenience function `MustLocalizeMessage` (#352) Added a must variant of `LocalizeMessage` (like `Localize` & `MustLocalize`) --- i18n/localizer.go | 11 ++++++++++- i18n/localizer_test.go | 11 +++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/i18n/localizer.go b/i18n/localizer.go index b13160fe..a3a23599 100644 --- a/i18n/localizer.go +++ b/i18n/localizer.go @@ -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, @@ -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 +} diff --git a/i18n/localizer_test.go b/i18n/localizer_test.go index 5856ec6b..77104790 100644 --- a/i18n/localizer_test.go +++ b/i18n/localizer_test.go @@ -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{}) +}