From 89f45d7aa83a4bb8347c80404b5856e648e14731 Mon Sep 17 00:00:00 2001 From: "marko.tikvic" Date: Tue, 17 Jul 2018 11:47:48 +0200 Subject: [PATCH] GetBestMatchLocale takes in *http.Request for simplicity --- localization.go | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/localization.go b/localization.go index 946bc15..7386f0e 100644 --- a/localization.go +++ b/localization.go @@ -2,8 +2,8 @@ package webutility import ( "encoding/json" - "fmt" "io/ioutil" + "net/http" "path" "strconv" "strings" @@ -67,10 +67,13 @@ func (d *Dictionary) AddTranslations(directory string) error { return nil } -func (d *Dictionary) GetBestMatchLocale(langs string) (best string) { - accepted := d.parseAcceptedLanguages(langs) +func (d *Dictionary) GetBestMatchLocale(req *http.Request) (best string) { + accepted := d.parseAcceptedLanguages(req.Header.Get("Accept-Language")) for i, _ := range accepted { + if accepted[i].Code == "*" { + return d.defaultLocale + } for j, _ := range d.supported { if accepted[i].Code == d.supported[j] { return d.supported[j] @@ -107,7 +110,7 @@ func (d *Dictionary) parseAcceptedLanguages(accepted string) (langs []LangWeight parts := strings.Split(accepted, ",") for i, _ := range parts { - parts[i] = strings.Trim(parts[i], "") + parts[i] = strings.Trim(parts[i], " ") var code string = "" var weight float64 = 0.0 @@ -122,16 +125,14 @@ func (d *Dictionary) parseAcceptedLanguages(accepted string) (langs []LangWeight } else if paramCount == 2 { // parse weight code = cw[0] - weight, _ = strconv.ParseFloat(cw[1], 64) + weight, _ = strconv.ParseFloat(cw[1][2:], 64) } - fmt.Println(parts[i], code, weight) - langs = append(langs, LangWeight{Code: code, Weight: weight}) } - // TODO(marko): sort langs by weights + // TODO(marko): sort langs by weights? return langs } -- 1.8.1.2