github.com/imannamdari/v2ray-core/v5@v5.0.5/infra/conf/merge/merge.go (about)

     1  // Copyright 2020 Jebbs. All rights reserved.
     2  // Use of this source code is governed by MIT
     3  // license that can be found in the LICENSE file.
     4  
     5  /*
     6  Package merge provides the capability to merge multiple
     7  JSON files or contents into one output.
     8  
     9  Merge Rules:
    10  
    11  - Simple values (string, number, boolean) are overwritten, others are merged
    12  - Elements with same "tag" (or "_tag") in an array will be merged
    13  - Add "_priority" property to array elements will help sort the
    14  */
    15  package merge
    16  
    17  import (
    18  	"bytes"
    19  	"encoding/json"
    20  
    21  	"github.com/imannamdari/v2ray-core/v5/infra/conf/serial"
    22  )
    23  
    24  // JSONs merges multiple json contents into one json.
    25  func JSONs(args [][]byte) ([]byte, error) {
    26  	m := make(map[string]interface{})
    27  	for _, arg := range args {
    28  		if _, err := ToMap(arg, m); err != nil {
    29  			return nil, err
    30  		}
    31  	}
    32  	return FromMap(m)
    33  }
    34  
    35  // ToMap merges json content to target map and returns it
    36  func ToMap(content []byte, target map[string]interface{}) (map[string]interface{}, error) {
    37  	if target == nil {
    38  		target = make(map[string]interface{})
    39  	}
    40  	r := bytes.NewReader(content)
    41  	n := make(map[string]interface{})
    42  	err := serial.DecodeJSON(r, &n)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  	if err = mergeMaps(target, n); err != nil {
    47  		return nil, err
    48  	}
    49  	return target, nil
    50  }
    51  
    52  // FromMap apply merge rules to map and convert it to json
    53  func FromMap(target map[string]interface{}) ([]byte, error) {
    54  	if target == nil {
    55  		target = make(map[string]interface{})
    56  	}
    57  	err := ApplyRules(target)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	return json.Marshal(target)
    62  }