Here are a few patterns you can use—each comes with a suggested method name, a little sketch of how it might look in Go, and (where applicable) a pointer to a real-world inspiration.
-
Method name: GetName(ctx context.Context)
Very “plain English” and obvious what you’re doing.
package model
import "context"
// language key for context
type langKey struct{}
// Helpers to set/get language in context
func WithLang(ctx context.Context, lang string) context.Context {
return context.WithValue(ctx, langKey{}, lang)
}
func LangFrom(ctx context.Context) string {
if lg, ok := ctx.Value(langKey{}).(string); ok && lg != "" {
return lg
}
return "en"
}
type Product struct {
NameEN string
NameID string
}
// GetName returns the name in the language stored in ctx.
func (p *Product) GetName(ctx context.Context) string {
switch LangFrom(ctx) {
case "id":
return p.NameID
default:
return p.NameEN
}
}
-
Method name: LocalizedName(ctx context.Context)
More explicit about “localized”/i18n. A lot of teams prefer this to make it clear it’s not just a getter.
func (p *Product) LocalizedName(ctx context.Context) string {
switch LangFrom(ctx) {
case "id":
return p.NameID
}
return p.NameEN
}
Inspiration: the Go-Cloud project uses very explicit names like MessageString, Printer, Localizer, etc., in golang.org/x/text.
-
Method name: Name(ctx context.Context)
This is the most idiomatic Go: call it simply Name, but take a context.Context parameter so callers know it can be influenced by context.
// Name returns the context-aware name (EN by default).
func (p *Product) Name(ctx context.Context) string { … }
Inspiration: you see this pattern in many Go APIs (e.g. io.Reader.Read, http.Client.Do(ctx,…))—the first argument is context.
-
Method name: NameByLocale(locale language.Tag)
If you want to be extra-explicit and avoid context gymnastics, you can pass a language.Tag from golang.org/x/text/language:
import "golang.org/x/text/language"
func (p *Product) NameByLocale(tag language.Tag) string {
switch tag.String() {
case "id":
return p.NameID
default:
return p.NameEN
}
}
Inspiration: the x/text package deals in language.Tag, message.Printer, etc.
-
Method name: T(ctx context.Context)
A tiny “gettext-style” alias. Some folks use a one-letter translator:
func (p *Product) T(ctx context.Context) string {
if LangFrom(ctx) == "id" {
return p.NameID
}
return p.NameEN
}
Inspiration: frameworks like Buffalo’s i18n use a T(…) function to translate message IDs.
All the sketches above can be adapted to pull the language from headers, JWT claims, a middleware, or any other source. Once you standardize on how you store “current language” in your context, plugging it into any of these method names is straightforward.