github.com/wfusion/gofusion@v1.1.14/http/i18n.go (about)

     1  package http
     2  
     3  import (
     4  	"strings"
     5  	"sync"
     6  
     7  	"github.com/gin-gonic/gin/binding"
     8  	"github.com/go-playground/locales/en"
     9  	"github.com/go-playground/locales/zh"
    10  	"github.com/go-playground/validator/v10"
    11  	"github.com/pkg/errors"
    12  	"golang.org/x/text/language"
    13  
    14  	"github.com/wfusion/gofusion/common/constant"
    15  	"github.com/wfusion/gofusion/common/utils"
    16  	"github.com/wfusion/gofusion/i18n"
    17  
    18  	ut "github.com/go-playground/universal-translator"
    19  	enT "github.com/go-playground/validator/v10/translations/en"
    20  	zhT "github.com/go-playground/validator/v10/translations/zh"
    21  )
    22  
    23  var (
    24  	I18n  i18n.Localizable[Errcode]
    25  	i18ns map[string]i18n.Localizable[Errcode]
    26  
    27  	ginBindingI18nOnce       = new(sync.Once)
    28  	ginBindingI18nTranslator ut.Translator
    29  )
    30  
    31  func Localizable(opts ...utils.OptionExtender) i18n.Localizable[Errcode] {
    32  	opt := utils.ApplyOptions[useOption](opts...)
    33  
    34  	locker.RLock()
    35  	defer locker.RUnlock()
    36  	i, ok := i18ns[opt.appName]
    37  	if !ok {
    38  		panic(errors.Errorf("http i18n not founc: %s", opt.appName))
    39  	}
    40  	return i
    41  }
    42  
    43  func ginBindingValidatorI18n(appName string) {
    44  	ginBindingI18nOnce.Do(func() {
    45  		var ok bool
    46  		engine, ok := binding.Validator.Engine().(*validator.Validate)
    47  		if !ok {
    48  			return
    49  		}
    50  
    51  		enLocales := en.New()
    52  		zhLocales := zh.New()
    53  		switch lang := i18n.DefaultLang(i18n.AppName(appName)); lang {
    54  		case language.English:
    55  			ginBindingI18nTranslator, ok = ut.New(enLocales, zhLocales, enLocales).GetTranslator(lang.String())
    56  			if !ok {
    57  				return
    58  			}
    59  			utils.MustSuccess(enT.RegisterDefaultTranslations(engine, ginBindingI18nTranslator))
    60  		default:
    61  			ginBindingI18nTranslator, ok = ut.New(zhLocales, zhLocales, enLocales).GetTranslator(lang.String())
    62  			if !ok {
    63  				return
    64  			}
    65  			utils.MustSuccess(zhT.RegisterDefaultTranslations(engine, ginBindingI18nTranslator))
    66  		}
    67  	})
    68  }
    69  
    70  func parseGinBindingValidatorError(src error) (dst error) {
    71  	e, ok := src.(validator.ValidationErrors)
    72  	if !ok || ginBindingI18nTranslator == nil {
    73  		return src
    74  	}
    75  	return errors.New(strings.Join(utils.MapValues(e.Translate(ginBindingI18nTranslator)), constant.LineBreak))
    76  }