Example #1
0
func getLanguage(w http.ResponseWriter, r *http.Request) string {
	var preferred []language.Tag
	var err error
	save := false

	r.ParseForm()
	lang := r.Form.Get("lang")
	if lang != "" {
		preferred, _, err = language.ParseAcceptLanguage(lang)
		if err != nil {
			// log err
		} else {
			save = true
		}
	}

	if preferred == nil {
		cookie, err := r.Cookie("lang")
		if err == nil {
			preferred, _, err = language.ParseAcceptLanguage(cookie.Value)
			if err != nil {
				// log err
			}
		}
	}

	if preferred == nil {
		preferred, _, err = language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
		if err != nil {
			// log err
		}
	}

	matcher := language.NewMatcher([]language.Tag{
		language.English,
		language.Italian,
		language.French,
	})
	code, _, _ := matcher.Match(preferred...)
	base, _ := code.Base()

	if save {
		now := time.Now()
		expires := now.AddDate(1, 0, 0)
		http.SetCookie(w, &http.Cookie{
			Name:    "lang",
			Value:   base.String(),
			Path:    "/",
			Expires: expires,
		})
	}

	return base.String()
}
Example #2
0
func localeFromRequest(request prago.Request) string {
	acceptHeader := request.Request().Header.Get("Accept-Language")

	t, _, _ := language.ParseAcceptLanguage(acceptHeader)
	tag, _, _ := languageMatcher.Match(t...)
	return tag.String()
}
Example #3
0
//SearchMessage parse Accept-Language header ,selects most-weighted(biggest q)
//language ,reads the associated message file, and creates and returns message obj.
func SearchMessage(acceptLanguage, filedir string) Message {
	const defaultLanguage = "en" // Language code (see RFC3066)

	var lang []string
	if strings.HasPrefix(acceptLanguage, "ja-") {
		acceptLanguage = "ja"
	}
	if acceptLanguage != "" {
		tags, _, err := language.ParseAcceptLanguage(acceptLanguage)
		if err != nil {
			log.Println(err)
		} else {
			for _, tag := range tags {
				lang = append(lang, tag.String())
			}
		}
	}
	lang = append(lang, defaultLanguage)
	for _, l := range lang {
		slang := strings.Split(l, "-")[0]
		for _, j := range []string{l, slang} {
			if m, err := newMessage(filedir, "message-"+j+".txt"); err == nil {
				return m
			}
		}
	}
	log.Fatalf("no messages are found.")
	return nil
}
//export preferredLanguageFromUseCString
func preferredLanguageFromUseCString(cHttpAcceptLanguage *C.char) *C.char {
	httpAcceptLanguage := C.GoString(cHttpAcceptLanguage)

	tag, _, _ := language.ParseAcceptLanguage(httpAcceptLanguage)
	t, _, _ := mather.Match(tag...)
	return C.CString(t.String())
}
//export preferredLanguageFrom
func preferredLanguageFrom(httpAcceptLanguage *string) *string {

	tag, _, _ := language.ParseAcceptLanguage(*httpAcceptLanguage)
	t, _, _ := mather.Match(tag...)
	l := t.String()
	return &l
}
Example #6
0
func ExampleParseAcceptLanguage() {
	// Tags are reordered based on their q rating. A missing q value means 1.0.
	fmt.Println(language.ParseAcceptLanguage(" nn;q=0.3, en-gb;q=0.8, en,"))

	m := language.NewMatcher([]language.Tag{language.Norwegian, language.Make("en-AU")})

	t, _, _ := language.ParseAcceptLanguage("da, en-gb;q=0.8, en;q=0.7")
	fmt.Println(m.Match(t...))

	// Danish is pretty close to Norwegian.
	t, _, _ = language.ParseAcceptLanguage(" da, nl")
	fmt.Println(m.Match(t...))

	// Output:
	// [en en-GB nn] [1 0.8 0.3] <nil>
	// en-AU 1 High
	// no 0 High
}
Example #7
0
File: search.go Project: zquestz/s
func parseAcceptLanguage(header string) string {
	tags, _, err := language.ParseAcceptLanguage(header)
	if err != nil {
		return ""
	}

	// Using the first Tag as Tags are sorted by highest weight first
	return tags[0].String()
}
// Guess is kami middleware that examines Accept-Language and sets
// the greeting to a better one if possible.
func Guess(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
    if tag, _, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language")); err == nil {
        for _, t := range tag {
            if g, ok := greetings[t]; ok {
                ctx = WithContext(ctx, g)
                return ctx
            }
        }
    }
    return ctx
}
Example #9
0
// parse the locale based on Accept-Language header. If no header found or the values are invalid,
// we fall back to en-US
func (r *Request) parseLocale() {

	tags, _, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
	if err != nil {
		logging.Warning("Could not parse accept lang header: %s", err)
		return
	}

	if len(tags) > 0 {
		logging.Debug("Locale for request: %s", tags[0])
		r.Locale = tags[0].String()
	}
}
func GetAcceptLanguageResponse(r *http.Request, mr *MainResponse) {
	httpAcceptLanguageHeader := strings.Join(r.Header["Accept-Language"], ",")

	languageTags, _, _ := language.ParseAcceptLanguage(httpAcceptLanguageHeader)

	languages := make([]string, len(languageTags))
	for i := 0; i < len(languages); i++ {
		code := languageTags[i].String()
		languages[i] = code
	}

	mr.AcceptedLanguages = languages
}
Example #11
0
// CleanAcceptLanguage parses, cleans and returns the contents of a Accept-Language header.
// If an error is encountered, the returned string is the same as given.
func CleanAcceptLanguage(s string) (string, error) {
	tt, q, err := language.ParseAcceptLanguage(s)
	if err != nil {
		return s, err
	}

	s = ""
	for i := 0; i < len(tt); i++ {
		if i > 0 {
			s += ","
		}
		s += fmt.Sprintf("%s;q=%g", tt[i].String(), q[i])
	}
	return s, nil
}
// Detect Language from accept-language
func DetectLanguage(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
	lang := ""
	if tags, _, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language")); err == nil {
		if len(tags) > 0 {
			t := tags[0]
			base, _, _ := t.Raw() // base, sscript, region
			if base == japaneseBase {
				lang = "ja-JP"
			} else if t == language.AmericanEnglish {
				lang = "en-US"
			}
		}
	}
	ctx = LangWithContext(lang, ctx)
	return ctx
}
Example #13
0
func (self *Installer) HandleInstallerGet(wr http.ResponseWriter, r *http.Request) {
	if !self.hasTranslations {
		t, _, _ := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
		locale := ""
		if len(t) > 0 {
			locale = t[0].String()
		}
		InitI18n(locale, filepath.Join("contrib", "translations"))
		self.hasTranslations = true
	}
	if self.currentNode == nil {
		wr.WriteHeader(404)
	} else {
		m := self.currentNode.model(self.currentNode, self.currentErr, self.config)
		template.writeTemplate(self.currentNode.templateName, m, wr)
	}
}
Example #14
0
// PopulateTransactionLanguage populates transaction Language fields from request Accept-Language field,
// choosing most-scored (q-ed) language base.
//
// WARNING: this method is NOT THREAD-SAFE, so shouldn't be called from unsynchronized threads
// (transaction shouldn't be accessed/modified by other threads, while this method is running)
func (engine *Engine) PopulateTransactionLanguage(transaction *Transaction) {

	if transaction.AcceptLanguage == "" {
		return
	}

	tags, _, err := language.ParseAcceptLanguage(transaction.AcceptLanguage)
	if err != nil {
		transaction.RegisterErrorMessage(fmt.Sprintf("Engine.PopulateTransactionLanguage(): language.ParseAcceptLanguage(): %v", err))
		return
	}

	if len(tags) <= 0 {
		return
	}

	base, _ := tags[0].Base()

	transaction.LanguageCode = base.String()

}
func (handler *LocaleHandler) determineLocalizedDir(locale string) string {
	tags, _, err := language.ParseAcceptLanguage(locale)
	if (err != nil) || (len(tags) == 0) {
		return defaultDir
	}

	for _, tag := range tags {
		matchedLocale := ""
		for _, l := range handler.SupportedLocales {
			base, _ := tag.Base()
			if l == base.String() {
				matchedLocale = l
				break
			}
		}
		localeDir := "./public/" + matchedLocale
		if matchedLocale != "" && handler.dirExists(localeDir) {
			return localeDir
		}
	}
	return defaultDir
}
Example #16
0
// handler is a http.HandlerFunc.
func handler(w http.ResponseWriter, r *http.Request) {
	t, q, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
	// We ignore the error: the default language will be selected for t == nil.
	tag, _, _ := matcher.Match(t...)
	fmt.Printf("%5v (t: %6v; q: %3v; err: %v)\n", tag, t, q, err)
}
Example #17
0
func Language(req *http.Request) language.Tag {
	tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language"))
	tag, _, _ := SupportedLanguageMatcher.Match(tags...)
	return tag
}
Example #18
0
// MatchString parses string s and matches the first of the given tags to reach a certain confidence threshold with an available locale.
// The string can be a single language tag or a list of language tags with preference values (from the Accept-Language header, for example).
func MatchString(s string) (language.Tag, language.Confidence) {
	pref, _, _ := language.ParseAcceptLanguage(s)
	return Match(pref...)
}