i18n.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2014 beego Author. All Rights Reserved.
  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. // Usage:
  15. //
  16. // import "github.com/astaxie/beego/middleware"
  17. //
  18. // I18N = middleware.NewLocale("conf/i18n.conf", beego.AppConfig.String("language"))
  19. //
  20. // more docs: http://beego.me/docs/module/i18n.md
  21. package middleware
  22. import (
  23. "encoding/json"
  24. "io/ioutil"
  25. "os"
  26. )
  27. type Translation struct {
  28. filepath string
  29. CurrentLocal string
  30. Locales map[string]map[string]string
  31. }
  32. func NewLocale(filepath string, defaultlocal string) *Translation {
  33. file, err := os.Open(filepath)
  34. if err != nil {
  35. panic("open " + filepath + " err :" + err.Error())
  36. }
  37. data, err := ioutil.ReadAll(file)
  38. if err != nil {
  39. panic("read " + filepath + " err :" + err.Error())
  40. }
  41. i18n := make(map[string]map[string]string)
  42. if err = json.Unmarshal(data, &i18n); err != nil {
  43. panic("json.Unmarshal " + filepath + " err :" + err.Error())
  44. }
  45. return &Translation{
  46. filepath: filepath,
  47. CurrentLocal: defaultlocal,
  48. Locales: i18n,
  49. }
  50. }
  51. func (t *Translation) SetLocale(local string) {
  52. t.CurrentLocal = local
  53. }
  54. func (t *Translation) Translate(key string, local string) string {
  55. if local == "" {
  56. local = t.CurrentLocal
  57. }
  58. if ct, ok := t.Locales[key]; ok {
  59. if v, o := ct[local]; o {
  60. return v
  61. }
  62. }
  63. return key
  64. }