i18n

package
v2.0.0-...-35d3a76 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2021 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package i18n provides support for looking up messages according to a set of locale preferences.

Create a Bundle to use for the lifetime of your application.

bundle := &i18n.Bundle{DefaultLanguage: language.English}

Load translations into your bundle during initialization.

bundle.LoadMessageFile("en-US.yaml")

Create a Localizer to use for a set of language preferences.

func(w http.ResponseWriter, r *http.Request) {
    lang := r.FormValue("lang")
    accept := r.Header.Get("Accept-Language")
    localizer := i18n.NewLocalizer(bundle, lang, accept)
}

Use the Localizer to lookup messages.

    localizer.MustLocalize(&i18n.LocalizeConfig{
	        DefaultMessage: &i18n.Message{
	            ID: "HelloWorld",
	            Other: "Hello World!",
	        },
    })

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Bundle

type Bundle struct {
	// DefaultLanguage is the default language of the bundle.
	DefaultLanguage language.Tag

	// UnmarshalFuncs is a map of file extensions to UnmarshalFuncs.
	UnmarshalFuncs map[string]UnmarshalFunc
	// contains filtered or unexported fields
}

Bundle stores a set of messages and pluralization rules. Most applications only need a single bundle that is initialized early in the application's lifecycle. It is not goroutine safe to modify the bundle while Localizers are reading from it.

func (*Bundle) AddMessages

func (b *Bundle) AddMessages(tag language.Tag, messages ...*Message) error

AddMessages adds messages for a language. It is useful if your messages are in a format not supported by ParseMessageFileBytes.

func (*Bundle) LanguageTags

func (b *Bundle) LanguageTags() []language.Tag

LanguageTags returns the list of language tags of all the translations loaded into the bundle

func (*Bundle) LoadMessageFile

func (b *Bundle) LoadMessageFile(path string) (*MessageFile, error)

LoadMessageFile loads the bytes from path and then calls ParseMessageFileBytes.

func (*Bundle) MustAddMessages

func (b *Bundle) MustAddMessages(tag language.Tag, messages ...*Message)

MustAddMessages is similar to AddMessages except it panics if an error happens.

func (*Bundle) MustLoadMessageFile

func (b *Bundle) MustLoadMessageFile(path string)

MustLoadMessageFile is similar to LoadTranslationFile except it panics if an error happens.

func (*Bundle) MustParseMessageFileBytes

func (b *Bundle) MustParseMessageFileBytes(buf []byte, path string)

MustParseMessageFileBytes is similar to ParseMessageFileBytes except it panics if an error happens.

func (*Bundle) ParseMessageFileBytes

func (b *Bundle) ParseMessageFileBytes(buf []byte, path string) (*MessageFile, error)

ParseMessageFileBytes parses the bytes in buf to add translations to the bundle.

The format of the file is everything after the last ".".

The language tag of the file is everything after the second to last "." or after the last path separator, but before the format.

func (*Bundle) RegisterUnmarshalFunc

func (b *Bundle) RegisterUnmarshalFunc(format string, unmarshalFunc UnmarshalFunc)

RegisterUnmarshalFunc registers an UnmarshalFunc for format.

type LocalizeConfig

type LocalizeConfig struct {
	// MessageID is the id of the message to lookup.
	// This field is ignored if DefaultMessage is set.
	MessageID string

	// TemplateData is the data passed when executing the message's template.
	// If TemplateData is nil and PluralCount is not nil, then the message template
	// will be executed with data that contains the plural count.
	TemplateData interface{}

	// PluralCount determines which plural form of the message is used.
	PluralCount interface{}

	// DefaultMessage is used if the message is not found in any message files.
	DefaultMessage *Message

	// Funcs is used to extend the Go template engine's built in functions
	Funcs template.FuncMap
}

LocalizeConfig configures a call to the Localize method on Localizer.

type Localizer

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

Localizer provides Localize and MustLocalize methods that return localized messages.

func NewLocalizer

func NewLocalizer(bundle *Bundle, langs ...string) *Localizer

NewLocalizer returns a new Localizer that looks up messages in the bundle according to the language preferences in langs. It can parse Accept-Language headers as defined in http://www.ietf.org/rfc/rfc2616.txt.

func (*Localizer) Localize

func (l *Localizer) Localize(lc *LocalizeConfig) (string, error)

Localize returns a localized message.

func (*Localizer) LocalizeWithTag

func (l *Localizer) LocalizeWithTag(lc *LocalizeConfig) (string, language.Tag, error)

LocalizeWithTag returns a localized message and the language tag.

func (*Localizer) MustLocalize

func (l *Localizer) MustLocalize(lc *LocalizeConfig) string

MustLocalize is similar to Localize, except it panics if an error happens.

Example
package main

import (
	"fmt"

	"github.com/shuguocloud/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := &i18n.Bundle{DefaultLanguage: language.English}
	localizer := i18n.NewLocalizer(bundle, "en")
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: &i18n.Message{
			ID:    "HelloWorld",
			Other: "Hello World!",
		},
	}))
}
Output:

Hello World!
Example (CustomTemplateDelims)
package main

import (
	"fmt"

	"github.com/shuguocloud/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := &i18n.Bundle{DefaultLanguage: language.English}
	localizer := i18n.NewLocalizer(bundle, "en")
	helloPersonMessage := &i18n.Message{
		ID:         "HelloPerson",
		Other:      "Hello <<.Name>>!",
		LeftDelim:  "<<",
		RightDelim: ">>",
	}
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: helloPersonMessage,
		TemplateData:   map[string]string{"Name": "Nick"},
	}))
}
Output:

Hello Nick!
Example (NoDefaultMessage)
package main

import (
	"fmt"

	"github.com/BurntSushi/toml"
	"github.com/shuguocloud/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := &i18n.Bundle{DefaultLanguage: language.English}
	bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
	bundle.MustParseMessageFileBytes([]byte(`
HelloWorld = "Hello World!"
`), "en.toml")
	bundle.MustParseMessageFileBytes([]byte(`
HelloWorld = "Hola Mundo!"
`), "es.toml")

	{
		localizer := i18n.NewLocalizer(bundle, "en-US")
		fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "HelloWorld"}))
	}
	{
		localizer := i18n.NewLocalizer(bundle, "es-ES")
		fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "HelloWorld"}))
	}
}
Output:

Hello World!
Hola Mundo!
Example (Plural)
package main

import (
	"fmt"

	"github.com/shuguocloud/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := &i18n.Bundle{DefaultLanguage: language.English}
	localizer := i18n.NewLocalizer(bundle, "en")
	catsMessage := &i18n.Message{
		ID:    "Cats",
		One:   "I have {{.PluralCount}} cat.",
		Other: "I have {{.PluralCount}} cats.",
	}
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: catsMessage,
		PluralCount:    1,
	}))
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: catsMessage,
		PluralCount:    2,
	}))
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: catsMessage,
		PluralCount:    "2.5",
	}))
}
Output:

I have 1 cat.
I have 2 cats.
I have 2.5 cats.
Example (Plural_template)
package main

import (
	"fmt"

	"github.com/shuguocloud/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := &i18n.Bundle{DefaultLanguage: language.English}
	localizer := i18n.NewLocalizer(bundle, "en")
	personCatsMessage := &i18n.Message{
		ID:    "PersonCats",
		One:   "{{.Name}} has {{.Count}} cat.",
		Other: "{{.Name}} has {{.Count}} cats.",
	}
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: personCatsMessage,
		PluralCount:    1,
		TemplateData: map[string]interface{}{
			"Name":  "Nick",
			"Count": 1,
		},
	}))
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: personCatsMessage,
		PluralCount:    2,
		TemplateData: map[string]interface{}{
			"Name":  "Nick",
			"Count": 2,
		},
	}))
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: personCatsMessage,
		PluralCount:    "2.5",
		TemplateData: map[string]interface{}{
			"Name":  "Nick",
			"Count": "2.5",
		},
	}))
}
Output:

Nick has 1 cat.
Nick has 2 cats.
Nick has 2.5 cats.
Example (Template)
package main

import (
	"fmt"

	"github.com/shuguocloud/go-i18n/v2/i18n"
	"golang.org/x/text/language"
)

func main() {
	bundle := &i18n.Bundle{DefaultLanguage: language.English}
	localizer := i18n.NewLocalizer(bundle, "en")
	helloPersonMessage := &i18n.Message{
		ID:    "HelloPerson",
		Other: "Hello {{.Name}}!",
	}
	fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{
		DefaultMessage: helloPersonMessage,
		TemplateData:   map[string]string{"Name": "Nick"},
	}))
}
Output:

Hello Nick!

type Message

type Message = internal.Message

Message is a string that can be localized.

type MessageFile

type MessageFile = internal.MessageFile

MessageFile represents a parsed message file.

type MessageNotFoundErr

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

MessageNotFoundErr is returned from Localize when a message could not be found.

func (*MessageNotFoundErr) Error

func (e *MessageNotFoundErr) Error() string

type UnmarshalFunc

type UnmarshalFunc = internal.UnmarshalFunc

UnmarshalFunc unmarshals data into v.

Jump to

Keyboard shortcuts

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