github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/infra/conf/v2jsonpb/v2jsonpb.go (about) 1 package v2jsonpb 2 3 import ( 4 "io" 5 6 "google.golang.org/protobuf/encoding/protojson" 7 "google.golang.org/protobuf/proto" 8 9 core "github.com/v2fly/v2ray-core/v5" 10 "github.com/v2fly/v2ray-core/v5/common" 11 "github.com/v2fly/v2ray-core/v5/common/buf" 12 "github.com/v2fly/v2ray-core/v5/common/cmdarg" 13 "github.com/v2fly/v2ray-core/v5/common/serial" 14 ) 15 16 //go:generate go run github.com/v2fly/v2ray-core/v5/common/errors/errorgen 17 18 func loadV2JsonPb(data []byte) (*core.Config, error) { 19 coreconf := &core.Config{} 20 jsonpbloader := &protojson.UnmarshalOptions{Resolver: anyresolverv2{serial.GetResolver()}, AllowPartial: true} 21 err := jsonpbloader.Unmarshal(data, &V2JsonProtobufFollower{coreconf.ProtoReflect()}) 22 if err != nil { 23 return nil, err 24 } 25 return coreconf, nil 26 } 27 28 func dumpV2JsonPb(config proto.Message) ([]byte, error) { 29 jsonpbdumper := &protojson.MarshalOptions{Resolver: anyresolverv2{serial.GetResolver()}, AllowPartial: true} 30 bytew, err := jsonpbdumper.Marshal(&V2JsonProtobufFollower{config.ProtoReflect()}) 31 if err != nil { 32 return nil, err 33 } 34 return bytew, nil 35 } 36 37 func DumpV2JsonPb(config proto.Message) ([]byte, error) { 38 return dumpV2JsonPb(config) 39 } 40 41 const FormatProtobufV2JSONPB = "v2jsonpb" 42 43 func init() { 44 common.Must(core.RegisterConfigLoader(&core.ConfigFormat{ 45 Name: []string{FormatProtobufV2JSONPB}, 46 Extension: []string{".v2pb.json", ".v2pbjson"}, 47 Loader: func(input interface{}) (*core.Config, error) { 48 switch v := input.(type) { 49 case string: 50 r, err := cmdarg.LoadArg(v) 51 if err != nil { 52 return nil, err 53 } 54 data, err := buf.ReadAllToBytes(r) 55 if err != nil { 56 return nil, err 57 } 58 return loadV2JsonPb(data) 59 case []byte: 60 return loadV2JsonPb(v) 61 case io.Reader: 62 data, err := buf.ReadAllToBytes(v) 63 if err != nil { 64 return nil, err 65 } 66 return loadV2JsonPb(data) 67 default: 68 return nil, newError("unknown type") 69 } 70 }, 71 })) 72 }