Lokyn is a simple lib to allow for easy localized applications developpement. Heavily inspired by Fyne lang package but with more of a standalone philosophy.
package main
import (
"embed"
"fmt"
"github.com/halsten-dev/lokyn"
"log"
)
//go:embed translations
var translations embed.FS
func main() {
lokyn.Init()
err := lokyn.AddTranslationFS(translations, "translations")
if err != nil {
log.Fatal(err)
}
lokyn.SetLanguage("en")
fmt.Println(lokyn.L("translate"))
fmt.Println(lokyn.P("apple", 2))
}SetLanguage sets the language for the whole process. That is what you want in
a desktop or CLI application, where one language is in use at a time.
A server is different: two requests in two languages are handled at once, and
SetLanguage from one of them changes what the other one renders. For those,
give each request its own localizer instead.
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lang := languageFor(r) // cookie, Accept-Language, user account...
ctx := lokyn.WithContext(r.Context(), lokyn.NewLocalizer(lang))
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, lokyn.LCtx(r.Context(), "translate"))
fmt.Fprintln(w, lokyn.PCtx(r.Context(), "apple", 2))
}NewLocalizer returns one shared localizer per language, built on first use, so
calling it on every request costs nothing. A *Localizer holds no mutable state
and is safe to use from any number of goroutines.
LCtx and PCtx fall back to the process-wide language when the context
carries no localizer, so an existing application can move to them one file at a
time.
A localizer can also be used directly, without a context:
fr := lokyn.NewLocalizer("fr")
fmt.Println(fr.L("translate"))
fmt.Println(fr.P("apple", 2))
fmt.Println(fr.Language()) // frproject root /
translations /
en.json
fr.json
{
"translation": "translation",
"apple": {
"one": "apple",
"other": "apples"
}
}{
"translation": "traduction",
"apple": {
"one": "pomme",
"other": "pommes"
}
}