github.com/erda-project/erda-infra@v1.0.9/providers/legacy/httpendpoints/i18n/locale_resource.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package i18n 16 17 import ( 18 "net/http" 19 20 i18nprovider "github.com/erda-project/erda-infra/providers/i18n" 21 ) 22 23 // LocaleResource . 24 type LocaleResource interface { 25 // Name() string 26 ExistKey(key string) bool 27 Get(key string, defaults ...string) string 28 GetTemplate(key string) *Template 29 } 30 31 type localeResource struct { 32 // name string 33 t i18nprovider.Translator 34 langs i18nprovider.LanguageCodes 35 } 36 37 // func (lr *localeResource) Name() string { return lr.name } 38 39 func (lr *localeResource) ExistKey(key string) bool { 40 text := lr.t.Get(lr.langs, key, "") 41 return len(text) > 0 42 } 43 44 func (lr *localeResource) Get(key string, defaults ...string) string { 45 if len(defaults) > 0 { 46 return lr.t.Get(lr.langs, key, defaults[0]) 47 } 48 return lr.t.Text(lr.langs, key) 49 } 50 51 func (lr *localeResource) GetTemplate(key string) *Template { 52 content := lr.t.Text(lr.langs, key) 53 return NewTemplate(key, content) 54 } 55 56 // WrapLocaleResource . 57 func WrapLocaleResource(t i18nprovider.Translator, langs i18nprovider.LanguageCodes) LocaleResource { 58 return &localeResource{ 59 t: t, 60 langs: langs, 61 } 62 } 63 64 type nopLocaleResource struct{} 65 66 func (lr *nopLocaleResource) ExistKey(key string) bool { return false } 67 func (lr *nopLocaleResource) Get(key string, defaults ...string) string { 68 if len(defaults) > 0 { 69 return defaults[0] 70 } 71 return key 72 } 73 func (lr *nopLocaleResource) GetTemplate(key string) *Template { 74 return NewTemplate(key, key) 75 } 76 77 // NewNopLocaleResource . 78 func NewNopLocaleResource() LocaleResource { 79 return &nopLocaleResource{} 80 } 81 82 // Language . 83 func Language(r *http.Request) i18nprovider.LanguageCodes { 84 lang := r.Header.Get("Lang") 85 if len(lang) <= 0 { 86 lang = r.Header.Get("Accept-Language") 87 } 88 langs, _ := i18nprovider.ParseLanguageCode(lang) 89 return langs 90 }