notification_response.go (1677B)
1 package pgproto3 2 3 import ( 4 "bytes" 5 "encoding/binary" 6 "encoding/json" 7 8 "github.com/jackc/pgio" 9 ) 10 11 type NotificationResponse struct { 12 PID uint32 13 Channel string 14 Payload string 15 } 16 17 // Backend identifies this message as sendable by the PostgreSQL backend. 18 func (*NotificationResponse) Backend() {} 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 *NotificationResponse) Decode(src []byte) error { 23 buf := bytes.NewBuffer(src) 24 25 pid := binary.BigEndian.Uint32(buf.Next(4)) 26 27 b, err := buf.ReadBytes(0) 28 if err != nil { 29 return err 30 } 31 channel := string(b[:len(b)-1]) 32 33 b, err = buf.ReadBytes(0) 34 if err != nil { 35 return err 36 } 37 payload := string(b[:len(b)-1]) 38 39 *dst = NotificationResponse{PID: pid, Channel: channel, Payload: payload} 40 return nil 41 } 42 43 // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. 44 func (src *NotificationResponse) Encode(dst []byte) []byte { 45 dst = append(dst, 'A') 46 sp := len(dst) 47 dst = pgio.AppendInt32(dst, -1) 48 49 dst = pgio.AppendUint32(dst, src.PID) 50 dst = append(dst, src.Channel...) 51 dst = append(dst, 0) 52 dst = append(dst, src.Payload...) 53 dst = append(dst, 0) 54 55 pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) 56 57 return dst 58 } 59 60 // MarshalJSON implements encoding/json.Marshaler. 61 func (src NotificationResponse) MarshalJSON() ([]byte, error) { 62 return json.Marshal(struct { 63 Type string 64 PID uint32 65 Channel string 66 Payload string 67 }{ 68 Type: "NotificationResponse", 69 PID: src.PID, 70 Channel: src.Channel, 71 Payload: src.Payload, 72 }) 73 }