i18n
The i18n package provides internationalization support using go-i18n/v2 . It loads YAML locale files, translates messages with template data, and detects the preferred language from HTTP request headers.
Import
import "github.com/gofastadev/gofasta/pkg/i18n"Key Types
I18nService
type I18nService struct {
bundle *i18n.Bundle
defaultLang string
}Key Functions
| Function | Signature | Description |
|---|---|---|
NewI18nService | func NewI18nService(localesDir string, defaultLang string) *I18nService | Loads locale YAML files from the given directory |
T | func (s *I18nService) T(lang, messageID string, data map[string]interface{}) string | Translates a message ID using the given language |
LangFromRequest | func (s *I18nService) LangFromRequest(r *http.Request) string | Extracts the preferred language from the Accept-Language header |
CreateDefaultLocaleFile | func CreateDefaultLocaleFile(localesDir string) | Creates a default English locale file if none exists |
Translation Files
Create YAML translation files in your locales directory. Each file is named by its locale code.
locales/en.yaml:
welcome:
other: "Welcome, {{.Name}}!"
not_found:
other: "Resource not found"
unauthorized:
other: "Authentication required"
forbidden:
other: "You don't have permission to access this resource"
validation_failed:
other: "Validation failed"
internal_error:
other: "An internal error occurred"locales/fr.yaml:
welcome:
other: "Bienvenue, {{.Name}} !"
not_found:
other: "Ressource introuvable"
unauthorized:
other: "Authentification requise"Usage
Basic Translation
translator := i18n.NewI18nService("locales/", "en")
msg := translator.T("en", "welcome", map[string]interface{}{"Name": "Jane"})
// -> "Welcome, Jane!"
msg = translator.T("fr", "welcome", map[string]interface{}{"Name": "Jane"})
// -> "Bienvenue, Jane !"Fallback to Default Language
When a message is not found in the requested language, the service falls back to the default language:
// If "internal_error" is not in fr.yaml, falls back to en.yaml
msg := translator.T("fr", "internal_error", nil)
// -> "An internal error occurred"Language Detection from Request
func (c *UserController) Create(w http.ResponseWriter, r *http.Request) {
lang := c.translator.LangFromRequest(r)
user, err := c.service.Create(r.Context(), input)
if err != nil {
msg := c.translator.T(lang, "internal_error", nil)
httputil.Error(w, errors.BadRequest(msg))
return
}
msg := c.translator.T(lang, "welcome", map[string]interface{}{"Name": user.Name})
httputil.Created(w, msg, user)
}Creating Default Locale Files
On first run, generate a default English locale file:
i18n.CreateDefaultLocaleFile("locales/")Configuration via config.yaml
i18n:
default_language: en
locales_dir: locales/Environment variables use the GOFASTA_ prefix (e.g., GOFASTA_I18N_DEFAULT_LANGUAGE).
Related Pages
- Middleware — Locale detection middleware
- Errors — Localized error messages
- Mailer — Localized email templates
Last updated on