github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/infra/conf/mergers/mergers.go (about)

     1  package mergers
     2  
     3  //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen
     4  
     5  import (
     6  	"strings"
     7  
     8  	core "github.com/v2fly/v2ray-core/v5"
     9  	"github.com/v2fly/v2ray-core/v5/common"
    10  	"github.com/v2fly/v2ray-core/v5/infra/conf/json"
    11  )
    12  
    13  func init() {
    14  	common.Must(RegisterMerger(makeMerger(
    15  		core.FormatJSON,
    16  		[]string{".json", ".jsonc"},
    17  		nil,
    18  	)))
    19  	common.Must(RegisterMerger(makeMerger(
    20  		core.FormatTOML,
    21  		[]string{".toml"},
    22  		json.FromTOML,
    23  	)))
    24  	common.Must(RegisterMerger(makeMerger(
    25  		core.FormatYAML,
    26  		[]string{".yml", ".yaml"},
    27  		json.FromYAML,
    28  	)))
    29  	common.Must(RegisterMerger(
    30  		&Merger{
    31  			Name:       core.FormatAuto,
    32  			Extensions: nil,
    33  			Merge:      Merge,
    34  		}),
    35  	)
    36  }
    37  
    38  // Merger is a configurable format merger for V2Ray config files.
    39  type Merger struct {
    40  	Name       string
    41  	Extensions []string
    42  	Merge      MergeFunc
    43  }
    44  
    45  // MergeFunc is a utility to merge V2Ray config from external source into a map and returns it.
    46  type MergeFunc func(input interface{}, m map[string]interface{}) error
    47  
    48  var (
    49  	mergersByName = make(map[string]*Merger)
    50  	mergersByExt  = make(map[string]*Merger)
    51  )
    52  
    53  // RegisterMerger add a new Merger.
    54  func RegisterMerger(format *Merger) error {
    55  	if _, found := mergersByName[format.Name]; found {
    56  		return newError(format.Name, " already registered.")
    57  	}
    58  	mergersByName[format.Name] = format
    59  
    60  	for _, ext := range format.Extensions {
    61  		lext := strings.ToLower(ext)
    62  		if f, found := mergersByExt[lext]; found {
    63  			return newError(ext, " already registered to ", f.Name)
    64  		}
    65  		mergersByExt[lext] = format
    66  	}
    67  
    68  	return nil
    69  }