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

     1  package i18n
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/BurntSushi/toml"
     7  	"github.com/nicksnyder/go-i18n/v2/i18n"
     8  	"golang.org/x/text/language"
     9  	"gopkg.in/yaml.v3"
    10  
    11  	"github.com/wfusion/gofusion/common/utils"
    12  	"github.com/wfusion/gofusion/common/utils/serialize/json"
    13  	"github.com/wfusion/gofusion/config"
    14  )
    15  
    16  func Construct(ctx context.Context, conf Conf, opts ...utils.OptionExtender) func() {
    17  	var err error
    18  	lang := defaultLang
    19  	if utils.IsStrNotBlank(conf.DefaultLang) {
    20  		if lang, err = language.Parse(conf.DefaultLang); err != nil {
    21  			panic(err)
    22  		}
    23  	}
    24  
    25  	opt := utils.ApplyOptions[config.InitOption](opts...)
    26  	optU := utils.ApplyOptions[useOption](opts...)
    27  	if opt.AppName == "" {
    28  		opt.AppName = optU.appName
    29  	}
    30  
    31  	locker.Lock()
    32  	defer locker.Unlock()
    33  	if Bundle == nil {
    34  		Bundle = &bundle[int]{
    35  			dup:    utils.NewSet[int](),
    36  			bundle: i18n.NewBundle(lang),
    37  		}
    38  		Bundle.bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
    39  		Bundle.bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
    40  		Bundle.bundle.RegisterUnmarshalFunc("yaml", yaml.Unmarshal)
    41  		Bundle.bundle.RegisterUnmarshalFunc("yml", yaml.Unmarshal)
    42  	}
    43  
    44  	// ioc
    45  	if opt.DI != nil {
    46  		opt.DI.
    47  			MustProvide(func() Localizable[int] { return NewBundle[int](lang) }).
    48  			MustProvide(func() Localizable[string] { return NewBundle[string](lang) })
    49  	}
    50  
    51  	return func() {
    52  		locker.Lock()
    53  		defer locker.Unlock()
    54  		Bundle = &bundle[int]{
    55  			dup:    utils.NewSet[int](),
    56  			bundle: i18n.NewBundle(lang),
    57  		}
    58  	}
    59  }
    60  
    61  type useOption struct {
    62  	appName string
    63  }
    64  
    65  func AppName(name string) utils.OptionFunc[useOption] {
    66  	return func(o *useOption) {
    67  		o.appName = name
    68  	}
    69  }
    70  
    71  func DefaultLang(opts ...utils.OptionExtender) (lang language.Tag) {
    72  	opt := utils.ApplyOptions[useOption](opts...)
    73  
    74  	conf := new(Conf)
    75  	utils.MustSuccess(config.Use(opt.appName).LoadComponentConfig(config.ComponentI18n, conf))
    76  	return utils.Must(language.Parse(conf.DefaultLang))
    77  }
    78  
    79  func init() {
    80  	config.AddComponent(config.ComponentI18n, Construct, config.WithFlag(&flagString))
    81  }