code.gitea.io/gitea@v1.19.3/modules/web/middleware/locale.go (about) 1 // Copyright 2020 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package middleware 5 6 import ( 7 "net/http" 8 9 "code.gitea.io/gitea/modules/setting" 10 "code.gitea.io/gitea/modules/translation" 11 "code.gitea.io/gitea/modules/translation/i18n" 12 13 "golang.org/x/text/language" 14 ) 15 16 // Locale handle locale 17 func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { 18 // 1. Check URL arguments. 19 lang := req.URL.Query().Get("lang") 20 changeLang := lang != "" 21 22 // 2. Get language information from cookies. 23 if len(lang) == 0 { 24 ck, _ := req.Cookie("lang") 25 if ck != nil { 26 lang = ck.Value 27 } 28 } 29 30 // Check again in case someone changes the supported language list. 31 if lang != "" && !i18n.DefaultLocales.HasLang(lang) { 32 lang = "" 33 changeLang = false 34 } 35 36 // 3. Get language information from 'Accept-Language'. 37 // The first element in the list is chosen to be the default language automatically. 38 if len(lang) == 0 { 39 tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language")) 40 tag := translation.Match(tags...) 41 lang = tag.String() 42 } 43 44 if changeLang { 45 SetLocaleCookie(resp, lang, 1<<31-1) 46 } 47 48 return translation.NewLocale(lang) 49 } 50 51 // SetLocaleCookie convenience function to set the locale cookie consistently 52 func SetLocaleCookie(resp http.ResponseWriter, lang string, expiry int) { 53 SetCookie(resp, "lang", lang, expiry, 54 setting.AppSubURL, 55 setting.SessionConfig.Domain, 56 setting.SessionConfig.Secure, 57 true, 58 SameSite(setting.SessionConfig.SameSite)) 59 } 60 61 // DeleteLocaleCookie convenience function to delete the locale cookie consistently 62 // Setting the lang cookie will trigger the middleware to reset the language to previous state. 63 func DeleteLocaleCookie(resp http.ResponseWriter) { 64 SetCookie(resp, "lang", "", 65 -1, 66 setting.AppSubURL, 67 setting.SessionConfig.Domain, 68 setting.SessionConfig.Secure, 69 true, 70 SameSite(setting.SessionConfig.SameSite)) 71 }