github.com/ydb-platform/ydb-go-sdk/v3@v3.57.0/topic/topicsugar/topicreader.go (about) 1 package topicsugar 2 3 import ( 4 "encoding/json" 5 6 "google.golang.org/protobuf/proto" 7 8 "github.com/ydb-platform/ydb-go-sdk/v3/topic/topicreader" 9 ) 10 11 // ProtoUnmarshal unmarshal message content to protobuf struct 12 func ProtoUnmarshal(msg *topicreader.Message, dst proto.Message) error { 13 return msg.UnmarshalTo(protobufUnmarshaler{dst: dst}) 14 } 15 16 // JSONUnmarshal unmarshal json message content to dst must by pointer to struct 17 func JSONUnmarshal(msg *topicreader.Message, dst interface{}) error { 18 return UnmarshalMessageWith(msg, json.Unmarshal, dst) 19 } 20 21 // UnmarshalMessageWith call unmarshaller func with message content 22 // unmarshaller func must not use received byte slice after return. 23 func UnmarshalMessageWith(msg *topicreader.Message, unmarshaler UnmarshalFunc, v interface{}) error { 24 return msg.UnmarshalTo(messageUnmarshaler{unmarshaler: unmarshaler, dst: v}) 25 } 26 27 // ReadMessageDataWithCallback receive full content of message as data slice MUST not be used after return from f. 28 // if you need content after return from function - copy it with 29 // copy(dst, data) to another byte slice 30 func ReadMessageDataWithCallback(msg *topicreader.Message, f func(data []byte) error) error { 31 return msg.UnmarshalTo(messageUnmarhalerToCallback(f)) 32 } 33 34 type messageUnmarhalerToCallback func(data []byte) error 35 36 // UnmarshalYDBTopicMessage unmarshal implementation 37 func (c messageUnmarhalerToCallback) UnmarshalYDBTopicMessage(data []byte) error { 38 return c(data) 39 } 40 41 // UnmarshalFunc is func to unmarshal data to interface, for example 42 // json.Unmarshal from standard library 43 type UnmarshalFunc func(data []byte, dst interface{}) error 44 45 type protobufUnmarshaler struct { 46 dst proto.Message 47 } 48 49 // UnmarshalYDBTopicMessage implement unmarshaller 50 func (m protobufUnmarshaler) UnmarshalYDBTopicMessage(data []byte) error { 51 return proto.Unmarshal(data, m.dst) 52 } 53 54 type messageUnmarshaler struct { 55 unmarshaler UnmarshalFunc 56 dst interface{} 57 } 58 59 // UnmarshalYDBTopicMessage implement unmarshaller 60 func (m messageUnmarshaler) UnmarshalYDBTopicMessage(data []byte) error { 61 return m.unmarshaler(data, m.dst) 62 }