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

     1  package helpers
     2  
     3  import (
     4  	"bytes"
     5  	"os"
     6  
     7  	"github.com/v2fly/v2ray-core/v5/infra/conf/merge"
     8  	"github.com/v2fly/v2ray-core/v5/infra/conf/mergers"
     9  	"github.com/v2fly/v2ray-core/v5/infra/conf/serial"
    10  	v4 "github.com/v2fly/v2ray-core/v5/infra/conf/v4"
    11  )
    12  
    13  // LoadConfig load config files to *conf.Config, it will:
    14  // - resolve folder to files
    15  // - try to read stdin if no file specified
    16  func LoadConfig(files []string, format string, recursively bool) (*v4.Config, error) {
    17  	m, err := LoadConfigToMap(files, format, recursively)
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  	bs, err := merge.FromMap(m)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  	r := bytes.NewReader(bs)
    26  	return serial.DecodeJSONConfig(r)
    27  }
    28  
    29  // LoadConfigToMap load config files to map, it will:
    30  // - resolve folder to files
    31  // - try to read stdin if no file specified
    32  func LoadConfigToMap(files []string, format string, recursively bool) (map[string]interface{}, error) {
    33  	var err error
    34  	if len(files) > 0 {
    35  		var extensions []string
    36  		extensions, err := mergers.GetExtensions(format)
    37  		if err != nil {
    38  			return nil, err
    39  		}
    40  		files, err = ResolveFolderToFiles(files, extensions, recursively)
    41  		if err != nil {
    42  			return nil, err
    43  		}
    44  	}
    45  	m := make(map[string]interface{})
    46  	if len(files) == 0 {
    47  		err = mergers.MergeAs(format, os.Stdin, m)
    48  	} else {
    49  		err = mergers.MergeAs(format, files, m)
    50  	}
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  	return m, nil
    55  }