Skip to content

Latest commit

 

History

10 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

lokyn

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.

main.go

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))
}

concurrent applications

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()) // fr

projects structure

project root /
  translations /
    en.json
    fr.json

en.json

{
  "translation": "translation", 
  "apple": {
	"one": "apple",
    "other": "apples"
  }
}

fr.json

{
  "translation": "traduction",
  "apple": {
	"one": "pomme",
	"other": "pommes"
  }
}

About

Lokyn is a simple lib to allow for easy localized applications developpement

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages