82 lines
1.7 KiB
Go
82 lines
1.7 KiB
Go
package translate
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"path"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const (
|
|
serviceKey contextKey = "translationService"
|
|
langKey contextKey = "language"
|
|
)
|
|
|
|
func Language(ctx context.Context) string {
|
|
lang, ok := ctx.Value(langKey).(string)
|
|
if !ok {
|
|
return ""
|
|
}
|
|
return lang
|
|
}
|
|
|
|
func SupportedLanguages(ctx context.Context) []string {
|
|
s, ok := ctx.Value(serviceKey).(*Service)
|
|
if !ok {
|
|
slog.Error("could not extract translation service from context for getting supported languages")
|
|
return []string{}
|
|
}
|
|
return s.SupportedLanguages()
|
|
}
|
|
|
|
func T(ctx context.Context, key string) string {
|
|
s, ok := ctx.Value(serviceKey).(*Service)
|
|
if !ok {
|
|
slog.Error("could not extract translation service from context", "ctx", ctx, "key", key)
|
|
return key
|
|
}
|
|
|
|
lang := Language(ctx)
|
|
|
|
translation, ok := s.translations[lang][key]
|
|
if !ok {
|
|
slog.Warn("could not translate", "key", key, "language", lang)
|
|
return key
|
|
}
|
|
|
|
return translation
|
|
}
|
|
|
|
func Path(ctx context.Context, pp ...string) string {
|
|
return PathForLang(ctx, Language(ctx), pp...)
|
|
}
|
|
|
|
func PathForLang(ctx context.Context, lang string, pp ...string) string {
|
|
s, ok := ctx.Value(serviceKey).(*Service)
|
|
if !ok {
|
|
slog.Error("could not extract translation service from context for translating path", "ctx", ctx, "path", pp)
|
|
return path.Join(pp...)
|
|
}
|
|
|
|
if len(pp) > 0 {
|
|
if _, ok := s.translations[pp[0]]; ok {
|
|
pp = pp[1:]
|
|
}
|
|
}
|
|
|
|
return "/" + path.Join(append([]string{lang}, pp...)...)
|
|
}
|
|
|
|
func (s *Service) SupportedLanguages() (languages []string) {
|
|
for lang := range s.translations {
|
|
languages = append(languages, lang)
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func (s *Service) DefaultLanguage() string {
|
|
return s.defaultLanguage
|
|
}
|