Use golang.org/x/text/language to detect locales and golang.org/x/text/message to format strings with the NewPrinter function.
package main
import (
"golang.org/x/text/language"
"golang.org/x/text/message"
"fmt"
)
func main() {
tag := language.MustParse("es")
p := message.NewPrinter(tag)
p.Printf("Hello, %s!\n", "World")
}
- Import the
languageandmessagepackages fromgolang.org/x/text. - Parse your target locale tag using
language.MustParse("en")orlanguage.MustParse("es"). - Create a new printer instance with
message.NewPrinter(tag). - Call
p.Printf()orp.Sprintf()to output localized strings. - Install the module by running
go get golang.org/x/text@latest.