i18n

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 12, 2025 License: MIT Imports: 13 Imported by: 0

README

rb - Reference Book

Generic reference book management package. Requires 1.18+ Alternative implementation of axkit/refbook using Go type parameters available from version 1.18

Example

Single Name Reference Book
type Item struct {
    ID          int     `json:"id"`
    Name        string  `json:"name"
    IsActive    bool    `json:"isActive"
}


func (item Item)PK() int {
    return item.ID
}

func (item Item)NameValue() string {
    return item.Name
}

b := rb.NewBook[Item](rb.WithNameSorting())
err := b.Parse([]byte(`[{"id": 1, "name": "Dog", "isActive": true}, {"id": 2, "name": "Cow", "isActive": true},
{"id": 3, "name":"Cat", "isActive": true}]`))

// or 

var db *dbw.DB
...
b := rb.NewBook[Item](rb.WithTable("items"), rb.WithNameSorting())
err = b.Cache(db)

s := b.Name(1)

Multi-language Name Reference Book
type MultiLangItem struct {
    ID          int             `json:"id"`
    Name        language.Name   `json:"name"
    IsActive    bool            `json:"isActive"
}


func (item MultiLangItem)PK() int {
    return item.ID
}

func (item MultiLangItem)NameValue(li language.Index) string {
    return item.Name.Elem(li)
}

b := rb.NewMultiLangBook[Item](rb.WithNameSorting())
err := b.Parse([]byte(`[{"id": 1, "name": {"en": "Dog", "cz": "Pes"}, "isActive": true}, 
{"id": 2, "name": {"en": "Cow", "cz": "Krava"}, "isActive": true}]`))

// or 

var db *dbw.DB
...
b := rb.NewBook[Item](rb.WithTable("animals"), rb.WithNameSorting())
err = b.Cache(db)

s := b.Name(1, language.ToIndex("en")) // Dog
s = b.Name(1, language.ToIndex("cz")) // Pes

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// NoValue represents a value that is found.
	NoValue = "$no_value$"
	// NoFoundIndex is used if language code is not found.
	NoFoundIndex = Unknown
)
View Source
var HintSeparator = "//"

HintSeparator holds a separator between value and hint in a .t18n file.

View Source
var NotFoundMarker = "\u2638"
View Source
var UnknownLanguageCode string = "?"

UnknownLanguageCode is used if Language is unknown.

Functions

func LanguageCodes

func LanguageCodes() []string

LanguageCodes returns copy of the slice of language codes.

func Len

func Len() int

Len returns number of supported languages.

func StringValidator

func StringValidator() func([]byte) bool

StringValidator returns function that validates jsonb data for String type.

Types

type AmazonS3FileStorage

type AmazonS3FileStorage struct{}

AmazonS3FileStorage implements the FileStorager interface for Amazon S3 files.

func NewAmazonS3FileStorage

func NewAmazonS3FileStorage() *AmazonS3FileStorage

func (*AmazonS3FileStorage) ExtractFilename

func (s *AmazonS3FileStorage) ExtractFilename(fullname string) (string, error)

ExtractFilename returns the file name from the full path.

func (*AmazonS3FileStorage) Filenames

func (s *AmazonS3FileStorage) Filenames(mask string, paths ...string) ([]string, error)

Filenames returns files from the directory specified by dir and mask.

func (*AmazonS3FileStorage) ParseFileName

func (lfr *AmazonS3FileStorage) ParseFileName(filename string) (li Language, suffix string)

ParseFileName returns the language index and suffix from the filename.

Example: ParseFileName("en.t18n") returns English, "" ParseFileName("en.grid.t18n") returns English, "grid"

func (*AmazonS3FileStorage) ReadFile

func (s *AmazonS3FileStorage) ReadFile(fullname string) ([]byte, error)

ReadFile reads the file content specified by fullname.

type ContainerOption

type ContainerOption func(o *containerConfig)

func WithBrackets

func WithBrackets(bracketSymbol string) ContainerOption

WithBrackets assigns wrapping symbol used by the client. Example: if bracketSymbol is "%", then the client will receive ["%hello%": "ahoj", "%bye%": "cau", "%Hello%": "Ahoj"]

func WithCustomFileParser

func WithCustomFileParser(parser FileContentParser) ContainerOption

func WithFileSuffixes

func WithFileSuffixes(suffix ...string) ContainerOption

WithFileSuffixes assigns suffixes of translation files in the order of applying priority. The first suffix has the highest priority.

func WithPrimaryLanguage

func WithPrimaryLanguage(li Language) ContainerOption

WithPrimaryLanguage assigns a primary language.

func WithStorage

func WithStorage(storage FileStorager) ContainerOption

func WithStrategy

func WithStrategy(strategy TranslationRequestStrategy) ContainerOption

type DefaultParser

type DefaultParser struct{}

func (*DefaultParser) ParseFileContent

func (p *DefaultParser) ParseFileContent(data []byte) ([]Item, error)

type FileContentParser

type FileContentParser interface {
	ParseFileContent(data []byte) ([]Item, error)
}

FileContentParser is an interface wrapping the ParseFileContent method.

ParseFileContent receives a content of a file and returns a slice of items.

type FileStorager

type FileStorager interface {
	//Filenames(mask string, paths ...string) ([]string, error)
	RegisteredFilenames() []string
	ExtractFilename(fullname string) (string, error)
	ParseFilename(filename string) (Language, string)
	ReadFile(filename string) ([]byte, error)
}

FileStorager is an interface wrapping the methods for reading files.

FileNamesByMask returns filenames by a mask in directories. ExtractFilename extracts a filename from a full path. ParseFilename parses a filename and returns a language index and a custom suffix. ReadFile reads a file and returns its content.

type Item

type Item struct {
	Key   string
	Value string
	Hint  string
}

Item represents an item in a .t18n file.

type Language

type Language int

Language is index of the language in the slice of language codes.

const Unknown Language = -1

Unknown holds Language value for unknown language.

func LanguageCount

func LanguageCount() Language

LanguageCount returns last Language. It is used to iterate over all registered languages.

func Lookup

func Lookup(code string) Language

Lookup returns Language by language code. Returns Unknown if language code is not found.

func NextLanguage

func NextLanguage(li Language) Language

NextLanguage returns index of the next language code in the hierarchy. Returns Unknown if language index is invalid or is the last one (Unknown).

func Parse

func Parse(code string) Language

Parse parses language code and returns Language. If language code is not found, it adds it.

If language code is complex, like zh-Hans-CN, than adds zh-Hans-CN, zh-Hans, zh codes and returns index of the first added Language.

func (Language) String

func (li Language) String() string

String implements fmt.Stringer interface.

type LocalFileStorage

type LocalFileStorage struct {
	// contains filtered or unexported fields
}

LocalFileStorage implements the FileStorager interface for local files.

Example
// Init part

_ = Parse("en-US")
en := Parse("en")
de := Parse("de")

fs := NewLocalFileStorage()
if err := fs.RegisterFiles("*.t18n", "./testdata"); err != nil {
	fmt.Printf("file registration error: %v", err)
	return
}

tc := NewContainer(
	WithPrimaryLanguage(en),
	WithStorage(fs),
	WithBrackets("%"),
)

if err := tc.ReadRegisteredFiles(); err != nil {
	fmt.Printf("file registration error: %v", err)
	return
}

// API Request processing part
languageCodeFromHTTPRequest := "en-GB"
requestLi := Lookup(languageCodeFromHTTPRequest)

// get translation for the language code from the request
tr := tc.Lang(requestLi)

trn := tc.Namespace("customer1", Lookup("en-US"))

fmt.Println(tr.Value("%Lift%"))          // from ./testdata/en-GB.t18n
fmt.Println(tr.Value("%Save%"))          // from ./testdata/en.t18n
fmt.Println(tc.Lang(de).Value("%Save%")) // from ./testdata/de.t18n
fmt.Println(trn.Value("%Lift%"))         // from ./testdata/en-US.customer1.t18n
Output:

Elevator
Save
Speichern
Hoist

func NewLocalFileStorage

func NewLocalFileStorage() *LocalFileStorage

func (*LocalFileStorage) ExtractFilename

func (s *LocalFileStorage) ExtractFilename(fullname string) (string, error)

ExtractFilename returns the file name from the full path.

func (*LocalFileStorage) ParseFilename

func (s *LocalFileStorage) ParseFilename(filename string) (li Language, suffix string)

ParseFileName returns the language index and suffix from the filename.

Example: ParseFileName("en.t18n") returns English, "" ParseFileName("en.grid.t18n") returns English, "grid"

func (*LocalFileStorage) ReadFile

func (s *LocalFileStorage) ReadFile(fullname string) ([]byte, error)

ReadFile reads the file content specified by fullname.

func (*LocalFileStorage) RegisterFiles

func (s *LocalFileStorage) RegisterFiles(mask string, paths ...string) error

RegisterFiles registers files by mask in the directories specified by paths.

func (*LocalFileStorage) RegisteredFilenames

func (s *LocalFileStorage) RegisteredFilenames() []string

type ResponseItem

type ResponseItem struct {
	Value string `json:"v"`
	Hint  string `json:"h,omitempty"`
}

ResponseItem represents a row to be returned to the client.

type Set

type Set struct {
	// contains filtered or unexported fields
}

Set holds a set of items.

type String

type String []string

String holds decoded names. Index of the slice calculates by LangIndex. In the database it is stored as jsonb: {"en":"Name","cz":"Jméno","sr":"Име"}

func ToString

func ToString(b []byte) (String, error)

ToString decodes jsonb like `{"en":"Name","cz":"Jméno","sr":"Име"}` into String type.

func (String) Bytes

func (n String) Bytes() []byte

Bytes returns jsonb representation of the Name.

func (String) InLang

func (n String) InLang(li Language, opts ...StringOption) string

InLang returns string in language identified by code index.

func (String) MarshalJSON

func (n String) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface.

func (*String) Scan

func (n *String) Scan(value interface{}) error

Scan implements database/sql Scanner interface.

func (*String) UnmarshalJSON

func (n *String) UnmarshalJSON(buf []byte) error

UnmarshalJSON implements json.Unmarshaler interface.

func (String) Value

func (n String) Value() (driver.Value, error)

Value implements interface sql.Valuer

type StringOption

type StringOption func() string

func WithDefault

func WithDefault(s string) StringOption

type TranslationContainer

type TranslationContainer struct {
	// contains filtered or unexported fields
}

TranslationContainer is a store of all translated resource items.

func NewContainer

func NewContainer(opts ...func(o *containerConfig)) *TranslationContainer

NewContainer creates a new localization container.

func (*TranslationContainer) Lang

Lang returns a TranslationRequest in a specific language and default namespace.

func (*TranslationContainer) Namespace

func (tc *TranslationContainer) Namespace(namespace string, li Language) TranslationRequest

Namespace returns a TranslationRequest in a specific namespace.

func (*TranslationContainer) ReadRegisteredFiles

func (tc *TranslationContainer) ReadRegisteredFiles() error

ReadRegisteredFiles reads content of all registered files, parses and stores content in the container.

type TranslationRequest

type TranslationRequest struct {
	// contains filtered or unexported fields
}

TranslationRequest is a request for a translation container in a specific language.

func (TranslationRequest) Hint

func (tr TranslationRequest) Hint(key string) string

Hint returns a hint for a specific key.

func (TranslationRequest) JSON

func (tr TranslationRequest) JSON() ([]byte, error)

JSON returns translation in JSON format.

func (TranslationRequest) Value

func (tr TranslationRequest) Value(key string) string

Value returns a translation value for a specific key.

func (TranslationRequest) ValueWithDefault

func (tr TranslationRequest) ValueWithDefault(id string, notFoundValue string) string

type TranslationRequestStrategy

type TranslationRequestStrategy int8

TranslationRequestStrategy defines a strategy for handling missing translations.

const (
	ReturnResourceCode TranslationRequestStrategy = iota
	ReturnNotFoundVariable
	ReturnEmptyString
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL