github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/app/subscription/containers/jsonfieldarray/parser.go (about)

     1  package jsonfieldarray
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	"github.com/v2fly/v2ray-core/v5/app/subscription/containers"
     7  	"github.com/v2fly/v2ray-core/v5/common"
     8  )
     9  
    10  // NewJSONFieldArrayParser internal api
    11  func NewJSONFieldArrayParser() containers.SubscriptionContainerDocumentParser {
    12  	return newJSONFieldArrayParser()
    13  }
    14  
    15  func newJSONFieldArrayParser() containers.SubscriptionContainerDocumentParser {
    16  	return &parser{}
    17  }
    18  
    19  type parser struct{}
    20  
    21  type jsonDocument map[string]json.RawMessage
    22  
    23  func (p parser) ParseSubscriptionContainerDocument(rawConfig []byte) (*containers.Container, error) {
    24  	result := &containers.Container{}
    25  	result.Kind = "JsonFieldArray"
    26  	result.Metadata = make(map[string]string)
    27  
    28  	var doc jsonDocument
    29  	if err := json.Unmarshal(rawConfig, &doc); err != nil {
    30  		return nil, newError("failed to parse as json").Base(err)
    31  	}
    32  
    33  	for key, value := range doc {
    34  		switch value[0] {
    35  		case '[':
    36  			parsedArray, err := p.parseArray(value, "JsonFieldArray+"+key)
    37  			if err != nil {
    38  				return nil, newError("failed to parse as json array").Base(err)
    39  			}
    40  			result.ServerSpecs = append(result.ServerSpecs, parsedArray...)
    41  		case '{':
    42  			fallthrough
    43  		default:
    44  			result.Metadata[key] = string(value)
    45  		}
    46  	}
    47  
    48  	return result, nil
    49  }
    50  
    51  func (p parser) parseArray(rawConfig []byte, kindHint string) ([]containers.UnparsedServerConf, error) {
    52  	var result []json.RawMessage
    53  	if err := json.Unmarshal(rawConfig, &result); err != nil {
    54  		return nil, newError("failed to parse as json array").Base(err)
    55  	}
    56  	var ret []containers.UnparsedServerConf
    57  	for _, value := range result {
    58  		ret = append(ret, containers.UnparsedServerConf{
    59  			KindHint: kindHint,
    60  			Content:  []byte(value),
    61  		})
    62  	}
    63  	return ret, nil
    64  }
    65  
    66  func init() {
    67  	common.Must(containers.RegisterParser("JsonFieldArray", newJSONFieldArrayParser()))
    68  }