github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/main/formats/formats.go (about)

     1  package formats
     2  
     3  import (
     4  	"bytes"
     5  
     6  	core "github.com/v2fly/v2ray-core/v5"
     7  	"github.com/v2fly/v2ray-core/v5/common"
     8  	"github.com/v2fly/v2ray-core/v5/infra/conf/merge"
     9  	"github.com/v2fly/v2ray-core/v5/infra/conf/mergers"
    10  	"github.com/v2fly/v2ray-core/v5/infra/conf/serial"
    11  )
    12  
    13  func init() {
    14  	for _, formatName := range mergers.GetAllNames() {
    15  		loader, err := makeMergeLoader(formatName)
    16  		if err != nil {
    17  			panic(err)
    18  		}
    19  		if formatName == core.FormatAuto {
    20  			loader.Extension = nil
    21  		}
    22  		common.Must(core.RegisterConfigLoader(loader))
    23  	}
    24  }
    25  
    26  func makeMergeLoader(formatName string) (*core.ConfigFormat, error) {
    27  	extensions, err := mergers.GetExtensions(formatName)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  	return &core.ConfigFormat{
    32  		Name:      []string{formatName},
    33  		Extension: extensions,
    34  		Loader:    makeLoaderFunc(formatName),
    35  	}, nil
    36  }
    37  
    38  func makeLoaderFunc(formatName string) core.ConfigLoader {
    39  	return func(input interface{}) (*core.Config, error) {
    40  		m := make(map[string]interface{})
    41  		err := mergers.MergeAs(formatName, input, m)
    42  		if err != nil {
    43  			return nil, err
    44  		}
    45  		data, err := merge.FromMap(m)
    46  		if err != nil {
    47  			return nil, err
    48  		}
    49  		r := bytes.NewReader(data)
    50  		cf, err := serial.DecodeJSONConfig(r)
    51  		if err != nil {
    52  			return nil, err
    53  		}
    54  		return cf.Build()
    55  	}
    56  }