github.com/xmplusdev/xmcore@v1.8.11-0.20240412132628-5518b55526af/infra/conf/serial/builder.go (about)

     1  package serial
     2  
     3  import (
     4  	"io"
     5  
     6  	creflect "github.com/xmplusdev/xmcore/common/reflect"
     7  	"github.com/xmplusdev/xmcore/core"
     8  	"github.com/xmplusdev/xmcore/infra/conf"
     9  	"github.com/xmplusdev/xmcore/main/confloader"
    10  )
    11  
    12  func MergeConfigFromFiles(files []string, formats []string) (string, error) {
    13  	c, err := mergeConfigs(files, formats)
    14  	if err != nil {
    15  		return "", err
    16  	}
    17  
    18  	if j, ok := creflect.MarshalToJson(c); ok {
    19  		return j, nil
    20  	}
    21  	return "", newError("marshal to json failed.").AtError()
    22  }
    23  
    24  func mergeConfigs(files []string, formats []string) (*conf.Config, error) {
    25  	cf := &conf.Config{}
    26  	for i, file := range files {
    27  		newError("Reading config: ", file).AtInfo().WriteToLog()
    28  		r, err := confloader.LoadConfig(file)
    29  		if err != nil {
    30  			return nil, newError("failed to read config: ", file).Base(err)
    31  		}
    32  		c, err := ReaderDecoderByFormat[formats[i]](r)
    33  		if err != nil {
    34  			return nil, newError("failed to decode config: ", file).Base(err)
    35  		}
    36  		if i == 0 {
    37  			*cf = *c
    38  			continue
    39  		}
    40  		cf.Override(c, file)
    41  	}
    42  	return cf, nil
    43  }
    44  
    45  func BuildConfig(files []string, formats []string) (*core.Config, error) {
    46  	config, err := mergeConfigs(files, formats)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  	return config.Build()
    51  }
    52  
    53  type readerDecoder func(io.Reader) (*conf.Config, error)
    54  
    55  var ReaderDecoderByFormat = make(map[string]readerDecoder)
    56  
    57  func init() {
    58  	ReaderDecoderByFormat["json"] = DecodeJSONConfig
    59  	ReaderDecoderByFormat["yaml"] = DecodeYAMLConfig
    60  	ReaderDecoderByFormat["toml"] = DecodeTOMLConfig
    61  
    62  	core.ConfigBuilderForFiles = BuildConfig
    63  	core.ConfigMergedFormFiles = MergeConfigFromFiles
    64  }