mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-03-30 02:22:49 +00:00
- 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
51 lines
1.4 KiB
Go
51 lines
1.4 KiB
Go
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
|
|
}
|