gi18n_ctx.go 945 B

1234567891011121314151617181920212223242526272829303132333435
  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 "context"
  9. const (
  10. ctxLanguage = "I18nLanguage"
  11. )
  12. // WithLanguage append language setting to the context and returns a new context.
  13. func WithLanguage(ctx context.Context, language string) context.Context {
  14. if ctx == nil {
  15. ctx = context.TODO()
  16. }
  17. return context.WithValue(ctx, ctxLanguage, language)
  18. }
  19. // LanguageFromCtx retrieves and returns language name from context.
  20. // It returns an empty string if it is not set previously.
  21. func LanguageFromCtx(ctx context.Context) string {
  22. if ctx == nil {
  23. return ""
  24. }
  25. v := ctx.Value(ctxLanguage)
  26. if v != nil {
  27. return v.(string)
  28. }
  29. return ""
  30. }