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

     1  package jsonpb
     2  
     3  import (
     4  	"bytes"
     5  	"io"
     6  
     7  	"github.com/golang/protobuf/jsonpb"
     8  	"github.com/golang/protobuf/proto"
     9  
    10  	core "github.com/imannamdari/v2ray-core/v5"
    11  	"github.com/imannamdari/v2ray-core/v5/common"
    12  	"github.com/imannamdari/v2ray-core/v5/common/buf"
    13  	"github.com/imannamdari/v2ray-core/v5/common/cmdarg"
    14  	"github.com/imannamdari/v2ray-core/v5/common/serial"
    15  )
    16  
    17  //go:generate go run github.com/imannamdari/v2ray-core/v5/common/errors/errorgen
    18  
    19  func loadJSONPB(data io.Reader) (*core.Config, error) {
    20  	coreconf := &core.Config{}
    21  	jsonpbloader := &jsonpb.Unmarshaler{AnyResolver: serial.GetResolver()}
    22  	err := jsonpbloader.Unmarshal(data, coreconf)
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  	return coreconf, nil
    27  }
    28  
    29  func dumpJSONPb(config proto.Message, w io.Writer) error {
    30  	jsonpbdumper := &jsonpb.Marshaler{AnyResolver: serial.GetResolver()}
    31  	err := jsonpbdumper.Marshal(w, config)
    32  	if err != nil {
    33  		return err
    34  	}
    35  	return nil
    36  }
    37  
    38  func DumpJSONPb(config proto.Message, w io.Writer) error {
    39  	return dumpJSONPb(config, w)
    40  }
    41  
    42  const FormatProtobufJSONPB = "jsonpb"
    43  
    44  func init() {
    45  	common.Must(core.RegisterConfigLoader(&core.ConfigFormat{
    46  		Name:      []string{FormatProtobufJSONPB},
    47  		Extension: []string{".pb.json", ".pbjson"},
    48  		Loader: func(input interface{}) (*core.Config, error) {
    49  			switch v := input.(type) {
    50  			case string:
    51  				r, err := cmdarg.LoadArg(v)
    52  				if err != nil {
    53  					return nil, err
    54  				}
    55  				data, err := buf.ReadAllToBytes(r)
    56  				if err != nil {
    57  					return nil, err
    58  				}
    59  				return loadJSONPB(bytes.NewReader(data))
    60  			case []byte:
    61  				return loadJSONPB(bytes.NewReader(v))
    62  			case io.Reader:
    63  				data, err := buf.ReadAllToBytes(v)
    64  				if err != nil {
    65  					return nil, err
    66  				}
    67  				return loadJSONPB(bytes.NewReader(data))
    68  			default:
    69  				return nil, newError("unknown type")
    70  			}
    71  		},
    72  	}))
    73  }