gi18n_ctx.go 996 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gi18n implements internationalization and localization.
  7. package gi18n
  8. import (
  9. "context"
  10. "github.com/gogf/gf/v2/os/gctx"
  11. )
  12. const (
  13. ctxLanguage gctx.StrKey = "I18nLanguage"
  14. )
  15. // WithLanguage append language setting to the context and returns a new context.
  16. func WithLanguage(ctx context.Context, language string) context.Context {
  17. if ctx == nil {
  18. ctx = context.TODO()
  19. }
  20. return context.WithValue(ctx, ctxLanguage, language)
  21. }
  22. // LanguageFromCtx retrieves and returns language name from context.
  23. // It returns an empty string if it is not set previously.
  24. func LanguageFromCtx(ctx context.Context) string {
  25. if ctx == nil {
  26. return ""
  27. }
  28. v := ctx.Value(ctxLanguage)
  29. if v != nil {
  30. return v.(string)
  31. }
  32. return ""
  33. }