Documentation
¶
Overview ¶
Package i18n is a small, dependency-free internationalization helper: a message catalog (Bundle) loaded from nested JSON, with {placeholder} substitution, one/other pluralization, and a fallback locale. Request-scoped locale detection lives in Middleware.
Index ¶
- func Locale(c *fiber.Ctx) string
- func Middleware(b *Bundle, opts ...MWOption) fiber.Handler
- func N(c *fiber.Ctx, key string, n int, args M) string
- func T(c *fiber.Ctx, key string, args M) string
- type Bundle
- func (b *Bundle) Fallback() string
- func (b *Bundle) Has(locale string) bool
- func (b *Bundle) LoadFS(fsys fs.FS, dir string) error
- func (b *Bundle) LoadJSON(locale string, data []byte) error
- func (b *Bundle) LoadMap(locale string, nested map[string]any)
- func (b *Bundle) Locales() []string
- func (b *Bundle) Plural(locale, key string, n int, args M) string
- func (b *Bundle) Translate(locale, key string, args M) string
- type M
- type MWOption
- type Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Middleware ¶
Middleware resolves the request locale (query > cookie > Accept-Language > fallback) and stores it, with the bundle, for T/N/Locale.
Types ¶
type Bundle ¶
type Bundle struct {
// contains filtered or unexported fields
}
Bundle is a catalog of messages per locale.
Example ¶
package main
import (
"fmt"
"github.com/rahmadafandi/fibr/i18n"
)
func main() {
b := i18n.New(i18n.WithFallback("en"))
b.LoadMap("en", map[string]any{
"welcome": "Hello, {name}!",
"cart": map[string]any{"items": map[string]any{"one": "{n} item", "other": "{n} items"}},
})
fmt.Println(b.Translate("en", "welcome", i18n.M{"name": "Sam"}))
fmt.Println(b.Plural("en", "cart.items", 3, nil))
}
Output: Hello, Sam! 3 items
func (*Bundle) LoadFS ¶
LoadFS loads every <locale>.json file in dir of fsys (file base name is the locale).
func (*Bundle) LoadMap ¶
LoadMap merges a nested message map into locale (flattened to dotted keys).
type MWOption ¶
type MWOption func(*mwConfig)
MWOption configures the middleware.
func WithCookieKey ¶
WithCookieKey sets the cookie checked for the locale (default "lang").
func WithQueryKey ¶
WithQueryKey sets the query parameter checked for the locale (default "lang").