feat: translation middleware

This commit is contained in:
2026-03-02 22:37:11 +01:00
parent dd5e32cc4d
commit 9a1f7e0d99
35 changed files with 1467 additions and 83 deletions
+81
View File
@@ -0,0 +1,81 @@
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 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 {
slog.Info("path for lang", "path", pp)
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
}