code.gitea.io/gitea@v1.22.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/translation" 10 "code.gitea.io/gitea/modules/translation/i18n" 11 12 "golang.org/x/text/language" 13 ) 14 15 // Locale handle locale 16 func Locale(resp http.ResponseWriter, req *http.Request) translation.Locale { 17 // 1. Check URL arguments. 18 lang := req.URL.Query().Get("lang") 19 changeLang := lang != "" 20 21 // 2. Get language information from cookies. 22 if len(lang) == 0 { 23 ck, _ := req.Cookie("lang") 24 if ck != nil { 25 lang = ck.Value 26 } 27 } 28 29 // Check again in case someone changes the supported language list. 30 if lang != "" && !i18n.DefaultLocales.HasLang(lang) { 31 lang = "" 32 changeLang = false 33 } 34 35 // 3. Get language information from 'Accept-Language'. 36 // The first element in the list is chosen to be the default language automatically. 37 if len(lang) == 0 { 38 tags, _, _ := language.ParseAcceptLanguage(req.Header.Get("Accept-Language")) 39 tag := translation.Match(tags...) 40 lang = tag.String() 41 } 42 43 if changeLang { 44 SetLocaleCookie(resp, lang, 1<<31-1) 45 } 46 47 return translation.NewLocale(lang) 48 } 49 50 // SetLocaleCookie convenience function to set the locale cookie consistently 51 func SetLocaleCookie(resp http.ResponseWriter, lang string, maxAge int) { 52 SetSiteCookie(resp, "lang", lang, maxAge) 53 } 54 55 // DeleteLocaleCookie convenience function to delete the locale cookie consistently 56 // Setting the lang cookie will trigger the middleware to reset the language to previous state. 57 func DeleteLocaleCookie(resp http.ResponseWriter) { 58 SetSiteCookie(resp, "lang", "", -1) 59 }