i18n

package module
v0.0.0-...-0d86c5e Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2016 License: MIT Imports: 11 Imported by: 2

README

i18n

GoDoc Build Status Coverage Status Go Report Card

This package is a translation package for golang. It provides basic translation management and http routing.

storage := i18n.NewInMemoryStorage() // this is non persistent storage, for testing only
t := i18n.New(storage)

value := t.GetWithLangString("en-GB", "SomeKey")
if value != nil {
    // Translation exists
}else{
    // Translation does not exist
}

// OR

valueString := t.T("en-GB", "SomeKey")

// OR

valueString := t.T(language.BritishEnglish, "SomeKey")

It allows background synchronization with the storage for updating translations.

t := i18n.New(storage)
t.SetRefreshInterval(1 * time.Hour)
defer t.Close() // This must be called to stop the refresh goroutine

To use the http router you wrap your default router in the Router object. All URLs will be prefixed with the language code. A specific language will also be matched by a generic parent, so /en-GB/some/path will match en and be redirected to /en/some/path.

If no language is specified in the URL, or it is not supported the Accept-Language header will be used to determine language. If the Accept-Language header is not set then the default language will be used.

package main

import (
	"net/http"

	"github.com/ThatsMrTalbot/i18n"    
	"golang.org/x/text/language"
)

type SomeHandler struct {
    translations *i18n.I18n
}

func (handler *SomeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    language := GetLanguageFromRequest(r)

    value := handler.translations.T(language, "SomeKey")
    w.Write([]byte(value))
}

func main() {
    storage := i18n.NewInMemoryStorage()
    translations := i18n.New(storage)

    translations.Add(&i18n.Translation{
        Lang: language.English
        Key: "SomeKey",
        Value: "SomeValue"
    })

    defaultHandler := &SomeHandler{
        translations: translations,
    }

    matcher := NewMatcher(translations)

    http.ListenAndServe(":8080", matcher.Wrapper(defaultHandler))
}

You can also use it on conjunction with scaffold. In this case the language is stored in the context.

package main

import (
	"net/http"

    "github.com/ThatsMrTalbot/i18n"    
	"github.com/ThatsMrTalbot/scaffold"    
	"golang.org/x/text/language"
    "golang.org/x/net/context"
)

type SomeHandler struct {
    translations *i18n.I18n
}

func (handler *SomeHandler) CtxServeHTTP(ctx context.Context, w http.ResponseWriter, r *http.Request) {
    language := GetLanguageFromContext(r)

    value := handler.translations.T(language, "SomeKey")
    w.Write([]byte(value))
}

func main() {
    storage := i18n.NewInMemoryStorage()
    translations := i18n.New(storage)

    translations.Add(&i18n.Translation{
        Lang: language.English
        Key: "SomeKey",
        Value: "SomeValue"
    })

    matcher := NewMatcher(translations)

    defaultHandler := &SomeHandler{
        translations: translations,
    }

    dispatcher := scaffold.DefaultDispatcher()
    router := scaffold.New(dispatcher)

    router.Use(matcher.Middleware())

    // Since all URLs will be prefixed by a language, you must take
    // that into consideration when routing
    router.Route(":lang").Handle("", defaultHandler)

    http.ListenAndServe(":8080", dispatcher)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetLanguageFromContext

func GetLanguageFromContext(ctx context.Context) language.Tag

GetLanguageFromContext returns the language from the context

func GetLanguageFromRequest

func GetLanguageFromRequest(r *http.Request) language.Tag

GetLanguageFromRequest gets the language from the internal map

func NewLanguageContext

func NewLanguageContext(ctx context.Context, tag language.Tag) context.Context

NewLanguageContext stores a language tag in the context

Types

type Cache

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

Cache stores translations in a map for fast access

func (*Cache) Add

func (cache *Cache) Add(translation *Translation)

Add translation to cache

func (*Cache) Clear

func (cache *Cache) Clear()

Clear translation cache

func (*Cache) Delete

func (cache *Cache) Delete(translation *Translation)

Delete translation from cache

func (*Cache) Get

func (cache *Cache) Get(lang language.Tag, key string) *Translation

Get translation from cache

type Group

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

Group is a translation subgroup

func (*Group) Add

func (group *Group) Add(translation *Translation) error

Add translation

func (*Group) Delete

func (group *Group) Delete(translation *Translation) error

Delete translation

func (*Group) GenerateHelper

func (group *Group) GenerateHelper(tag language.Tag) T

GenerateHelper generates a method that allways gets tags in a certain language This is usefull for passing to the template engine

func (*Group) Get

func (group *Group) Get(lang language.Tag, key string) *Translation

Get translation

func (*Group) GetWithLangString

func (group *Group) GetWithLangString(lang string, key string) (*Translation, error)

GetWithLangString parses the lang string before lookip up the translation

func (*Group) Group

func (group *Group) Group(key string) *Group

Group gets a translation group

func (*Group) T

func (group *Group) T(lang interface{}, key string) string

T is a helper method to get translation by lang string or language tag

type I18n

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

I18n defines basic translation get/set methods

func New

func New(storage ...Storage) *I18n

New translation manager

func (*I18n) Add

func (i18n *I18n) Add(translation *Translation) error

Add translation

func (*I18n) AddSupportedLanguage

func (i18n *I18n) AddSupportedLanguage(tags ...language.Tag) error

AddSupportedLanguage adds a supported language in storage

func (*I18n) Close

func (i18n *I18n) Close() error

Close must be called before going out of scope to stop the refresh goroutine

func (*I18n) Delete

func (i18n *I18n) Delete(translation *Translation) error

Delete translation

func (*I18n) GenerateHelper

func (i18n *I18n) GenerateHelper(tag language.Tag) T

GenerateHelper generates a method that allways gets tags in a certain language This is usefull for passing to the template engine

func (*I18n) Get

func (i18n *I18n) Get(lang language.Tag, key string) *Translation

Get translation

func (*I18n) GetDefaultLanguage

func (i18n *I18n) GetDefaultLanguage() language.Tag

GetDefaultLanguage gets the default language from storage

func (*I18n) GetSupportedLanguages

func (i18n *I18n) GetSupportedLanguages() []language.Tag

GetSupportedLanguages gets the supported languages from storage

func (*I18n) GetWithLangString

func (i18n *I18n) GetWithLangString(lang string, key string) (*Translation, error)

GetWithLangString parses the lang string before lookip up the translation

func (*I18n) Group

func (i18n *I18n) Group(key string) *Group

Group gets a translation group

func (*I18n) RemoveSupportedLanguage

func (i18n *I18n) RemoveSupportedLanguage(tag language.Tag) error

RemoveSupportedLanguage removes a supported language in storage

func (*I18n) SetDefaultLanguage

func (i18n *I18n) SetDefaultLanguage(tag language.Tag) error

SetDefaultLanguage sets the default language in storage

func (*I18n) SetRefreshInterval

func (i18n *I18n) SetRefreshInterval(d time.Duration)

SetRefreshInterval sets the inerval to sync the translations, 0 means no sync

func (*I18n) Sync

func (i18n *I18n) Sync() error

Sync translations with database

func (*I18n) T

func (i18n *I18n) T(lang interface{}, key string) string

T is a helper method to get translation by lang string or language tag

type Matcher

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

Matcher get parses languages from http requests

func NewMatcher

func NewMatcher(i18n *I18n) *Matcher

NewMatcher creates a new matcher

func (*Matcher) Middleware

func (matcher *Matcher) Middleware() scaffold.Middleware

Middleware returns scaffold.Middleware that stores the language in the context redirecting if necessary

func (*Matcher) Wrapper

func (matcher *Matcher) Wrapper(handler http.Handler) http.Handler

Wrapper returns a http.Handler that stores languages in a sharded map for retrieval using GetLanguageFromRequest

type Storage

type Storage interface {
	GetAll() ([]*Translation, error)
	Store(*Translation) error
	Delete(*Translation) error

	DefaultLanguage() (language.Tag, error)
	SupportedLanguages() ([]language.Tag, error)

	SetDefaultLanguage(language.Tag) error
	StoreSupportedLanguage(language.Tag) error
	DeleteSupportedLanguage(language.Tag) error
}

Storage interface

func NewInMemoryStorage

func NewInMemoryStorage() Storage

NewInMemoryStorage Creates a non persistent in memory translation store

type T

type T func(string) string

T is a function for getting a key from the storage

type Translation

type Translation struct {
	Lang  language.Tag
	Key   string
	Value string
}

Translation object

Directories

Path Synopsis
storage

Jump to

Keyboard shortcuts

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