gitea源码

locale.go 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2020 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package middleware
  4. import (
  5. "net/http"
  6. "code.gitea.io/gitea/modules/translation"
  7. "code.gitea.io/gitea/modules/translation/i18n"
  8. "golang.org/x/text/language"
  9. )
  10. // Locale handle locale
  11. func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale {
  12. // 1. Check URL arguments.
  13. lang := req.URL.Query().Get("lang")
  14. changeLang := lang != ""
  15. // 2. Get language information from cookies.
  16. if len(lang) == 0 {
  17. ck, _ := req.Cookie("lang")
  18. if ck != nil {
  19. lang = ck.Value
  20. }
  21. }
  22. // Check again in case someone changes the supported language list.
  23. if lang != "" && !i18n.DefaultLocales.HasLang(lang) {
  24. lang = ""
  25. changeLang = false
  26. }
  27. // 3. Get language information from 'Accept-Language'.
  28. // The first element in the list is chosen to be the default language automatically.
  29. if len(lang) == 0 {
  30. tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language"))
  31. tag := translation.Match(tags...)
  32. lang = tag.String()
  33. }
  34. if changeLang {
  35. SetLocaleCookie(resp, lang, 1<<31-1)
  36. }
  37. return translation.NewLocale(lang)
  38. }
  39. // SetLocaleCookie convenience function to set the locale cookie consistently
  40. func SetLocaleCookie(resp http.ResponseWriter, lang string, maxAge int) {
  41. SetSiteCookie(resp, "lang", lang, maxAge)
  42. }
  43. // DeleteLocaleCookie convenience function to delete the locale cookie consistently
  44. // Setting the lang cookie will trigger the middleware to reset the language to previous state.
  45. func DeleteLocaleCookie(resp http.ResponseWriter) {
  46. SetSiteCookie(resp, "lang", "", -1)
  47. }