mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-03-30 04:22:58 +00:00
feat(i18n): add backend multi-language support with user language preference
- Add go-i18n library for internationalization - Create i18n package with translation keys and YAML locale files (zh/en) - Implement i18n middleware for language detection from user settings and Accept-Language header - Add Language field to UserSetting DTO - Update API response helpers with i18n support (ApiErrorI18n, ApiSuccessI18n) - Migrate hardcoded messages in token, redemption, and user controllers - Add frontend language preference settings component - Sync language preference across header selector and user settings - Auto-restore user language preference on login
This commit is contained in:
50
middleware/i18n.go
Normal file
50
middleware/i18n.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
"github.com/QuantumNous/new-api/dto"
|
||||
"github.com/QuantumNous/new-api/i18n"
|
||||
)
|
||||
|
||||
// I18n middleware detects and sets the language preference for the request
|
||||
func I18n() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
lang := detectLanguage(c)
|
||||
c.Set(string(constant.ContextKeyLanguage), lang)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// detectLanguage determines the language preference for the request
|
||||
// Priority: 1. User setting (if logged in) -> 2. Accept-Language header -> 3. Default language
|
||||
func detectLanguage(c *gin.Context) string {
|
||||
// 1. Try to get language from user setting (set by auth middleware)
|
||||
if userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting); ok {
|
||||
if userSetting.Language != "" && i18n.IsSupported(userSetting.Language) {
|
||||
return userSetting.Language
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Parse Accept-Language header
|
||||
acceptLang := c.GetHeader("Accept-Language")
|
||||
if acceptLang != "" {
|
||||
lang := i18n.ParseAcceptLanguage(acceptLang)
|
||||
if i18n.IsSupported(lang) {
|
||||
return lang
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Return default language
|
||||
return i18n.DefaultLang
|
||||
}
|
||||
|
||||
// GetLanguage returns the current language from gin context
|
||||
func GetLanguage(c *gin.Context) string {
|
||||
if lang := c.GetString(string(constant.ContextKeyLanguage)); lang != "" {
|
||||
return lang
|
||||
}
|
||||
return i18n.DefaultLang
|
||||
}
|
||||
Reference in New Issue
Block a user