Add i18n support with English and Spanish translations
- Created i18n package with translator and middleware - Added translation files for English (en.json) and Spanish (es.json) - Updated all HTTP handlers to use i18n for error/success messages - Added comprehensive test coverage for i18n (87%) - Updated CI workflow to use Go 1.24 - All tests passing with 50.8% total coverage
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
package i18n
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/text/language"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const languageKey contextKey = "language"
|
||||
|
||||
func LanguageMiddleware(translator *Translator) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
acceptLanguage := r.Header.Get("Accept-Language")
|
||||
lang := translator.GetLanguage(acceptLanguage)
|
||||
ctx := context.WithValue(r.Context(), languageKey, lang)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func GetLanguageFromContext(ctx context.Context) language.Tag {
|
||||
if lang, ok := ctx.Value(languageKey).(language.Tag); ok {
|
||||
return lang
|
||||
}
|
||||
return language.English
|
||||
}
|
||||
Reference in New Issue
Block a user