copy_data.go (1453B)
1 package pgproto3 2 3 import ( 4 "encoding/hex" 5 "encoding/json" 6 7 "github.com/jackc/pgio" 8 ) 9 10 type CopyData struct { 11 Data []byte 12 } 13 14 // Backend identifies this message as sendable by the PostgreSQL backend. 15 func (*CopyData) Backend() {} 16 17 // Frontend identifies this message as sendable by a PostgreSQL frontend. 18 func (*CopyData) Frontend() {} 19 20 // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message 21 // type identifier and 4 byte message length. 22 func (dst *CopyData) Decode(src []byte) error { 23 dst.Data = src 24 return nil 25 } 26 27 // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. 28 func (src *CopyData) Encode(dst []byte) []byte { 29 dst = append(dst, 'd') 30 dst = pgio.AppendInt32(dst, int32(4+len(src.Data))) 31 dst = append(dst, src.Data...) 32 return dst 33 } 34 35 // MarshalJSON implements encoding/json.Marshaler. 36 func (src CopyData) MarshalJSON() ([]byte, error) { 37 return json.Marshal(struct { 38 Type string 39 Data string 40 }{ 41 Type: "CopyData", 42 Data: hex.EncodeToString(src.Data), 43 }) 44 } 45 46 // UnmarshalJSON implements encoding/json.Unmarshaler. 47 func (dst *CopyData) UnmarshalJSON(data []byte) error { 48 // Ignore null, like in the main JSON package. 49 if string(data) == "null" { 50 return nil 51 } 52 53 var msg struct { 54 Data string 55 } 56 if err := json.Unmarshal(data, &msg); err != nil { 57 return err 58 } 59 60 dst.Data = []byte(msg.Data) 61 return nil 62 }