i18n.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2019 Yunion
  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. package appctx
  15. import (
  16. "context"
  17. "net/http"
  18. "golang.org/x/text/language"
  19. )
  20. type ctxLang uintptr
  21. const (
  22. ctxLangKey = ctxLang(0)
  23. )
  24. var (
  25. defaultLang = language.English
  26. )
  27. func WithLangTag(ctx context.Context, tag language.Tag) context.Context {
  28. return context.WithValue(ctx, ctxLangKey, tag)
  29. }
  30. func WithLang(ctx context.Context, lang string) context.Context {
  31. tag, err := language.Parse(lang)
  32. if err != nil {
  33. tag = defaultLang
  34. }
  35. return WithLangTag(ctx, tag)
  36. }
  37. func WithRequestLang(ctx context.Context, req *http.Request) context.Context {
  38. if val := req.URL.Query().Get("lang"); val != "" {
  39. return WithLang(ctx, val)
  40. }
  41. if val := req.Header.Get(LangHeader); val != "" {
  42. return WithLang(ctx, val)
  43. }
  44. if cookie, err := req.Cookie("lang"); err == nil {
  45. return WithLang(ctx, cookie.Value)
  46. }
  47. return WithLangTag(ctx, defaultLang)
  48. }
  49. func Lang(ctx context.Context) language.Tag {
  50. var (
  51. langv = ctx.Value(ctxLangKey)
  52. lang language.Tag
  53. )
  54. if langv != nil {
  55. lang = langv.(language.Tag)
  56. } else {
  57. lang = defaultLang
  58. }
  59. return lang
  60. }
  61. const (
  62. LangHeader = "X-Yunion-Lang"
  63. )
  64. func SetHTTPLangHeader(ctx context.Context, header http.Header) bool {
  65. langv := ctx.Value(ctxLangKey)
  66. langTag, ok := langv.(language.Tag)
  67. if ok {
  68. header.Set(LangHeader, langTag.String())
  69. }
  70. return ok
  71. }