func TestNew(t *testing.T) { tests := []struct { localeID string lang *language.Language }{ {"en-US", language.LanguageWithID("en")}, {"en_US", language.LanguageWithID("en")}, {"zh-CN", language.LanguageWithID("zh")}, {"zh-TW", language.LanguageWithID("zh")}, {"pt-BR", language.LanguageWithID("pt-BR")}, {"pt_BR", language.LanguageWithID("pt-BR")}, {"pt-PT", language.LanguageWithID("pt")}, {"pt_PT", language.LanguageWithID("pt")}, {"zh-Hans-CN", nil}, {"zh-Hant-TW", nil}, {"xx-Yyen-US", nil}, {"en US", nil}, {"en-US-en-US", nil}, {".en-US..en-US.", nil}, } for _, test := range tests { loc, err := New(test.localeID) if loc == nil && test.lang != nil { t.Errorf("New(%q) = <nil>, %q; expected %q, <nil>", test.localeID, err, test.lang) } if loc != nil && loc.Language != test.lang { t.Errorf("New(%q) = %q; expected %q", test.localeID, loc.Language, test.lang) } } }
// New searches s for a valid language tag as defined by RFC 5646. // // It returns an error if s doesn't contain exactly one language tag or // if the language represented by the tag is not supported by this package. func New(s string) (*Locale, error) { matches := languageTagRegexp.FindAllStringSubmatch(s, -1) if count := len(matches); count != 1 { return nil, fmt.Errorf("%d locales found in string %s", count, s) } id, languageCode := matches[0][0], matches[0][1] language := language.LanguageWithID(languageCode) if language == nil { return nil, fmt.Errorf("unknown language code %s", languageCode) } return &Locale{id, language}, nil }
// New searches s for a valid language tag (RFC 5646) // of the form xx-YY or xx_YY where // xx is a 2 character language code and // YY is a 2 character country code. // // It returns an error if s doesn't contain exactly one language tag or // if the language represented by the tag is not supported by this package. func New(s string) (*Locale, error) { parts := tagSplitter.Split(s, -1) var id, lc string count := 0 for _, part := range parts { if tag := tagMatcher.FindStringSubmatch(part); tag != nil { count += 1 id, lc = tag[0], tag[1] } } if count != 1 { return nil, fmt.Errorf("%d locales found in string %s", count, s) } id = strings.Replace(id, "_", "-", -1) lang := language.LanguageWithID(id) if lang == nil { lang = language.LanguageWithID(lc) } if lang == nil { return nil, fmt.Errorf("unknown language %s", id) } return &Locale{id, lang}, nil }