You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.1 KiB

package httpapi
import (
"strconv"
"strings"
)
// selectLocale negotiates the two translations shipped by the foundation.
// Unknown language ranges are ignored and Spanish is the safe fallback.
func selectLocale(header string) string {
selected := "es"
bestWeight := -1.0
for index, item := range strings.Split(header, ",") {
if index >= 20 {
break
}
parts := strings.Split(strings.TrimSpace(item), ";")
language := strings.ToLower(strings.TrimSpace(parts[0]))
locale := ""
switch {
case language == "es" || strings.HasPrefix(language, "es-"):
locale = "es"
case language == "en" || strings.HasPrefix(language, "en-"):
locale = "en"
default:
continue
}
weight := 1.0
if len(parts) > 1 {
if len(parts) != 2 || !strings.HasPrefix(strings.TrimSpace(parts[1]), "q=") {
continue
}
parsed, err := strconv.ParseFloat(strings.TrimPrefix(strings.TrimSpace(parts[1]), "q="), 64)
if err != nil || parsed < 0 || parsed > 1 {
continue
}
weight = parsed
}
if weight > bestWeight && weight > 0 {
bestWeight = weight
selected = locale
}
}
return selected
}

Powered by TurnKey Linux.