notification_response.go (1810B)
1 package pgproto3 2 3 import ( 4 "bytes" 5 "encoding/binary" 6 "encoding/json" 7 8 "github.com/jackc/pgx/v5/internal/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 if buf.Len() < 4 { 26 return &invalidMessageFormatErr{messageType: "NotificationResponse", details: "too short"} 27 } 28 29 pid := binary.BigEndian.Uint32(buf.Next(4)) 30 31 b, err := buf.ReadBytes(0) 32 if err != nil { 33 return err 34 } 35 channel := string(b[:len(b)-1]) 36 37 b, err = buf.ReadBytes(0) 38 if err != nil { 39 return err 40 } 41 payload := string(b[:len(b)-1]) 42 43 *dst = NotificationResponse{PID: pid, Channel: channel, Payload: payload} 44 return nil 45 } 46 47 // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. 48 func (src *NotificationResponse) Encode(dst []byte) []byte { 49 dst = append(dst, 'A') 50 sp := len(dst) 51 dst = pgio.AppendInt32(dst, -1) 52 53 dst = pgio.AppendUint32(dst, src.PID) 54 dst = append(dst, src.Channel...) 55 dst = append(dst, 0) 56 dst = append(dst, src.Payload...) 57 dst = append(dst, 0) 58 59 pgio.SetInt32(dst[sp:], int32(len(dst[sp:]))) 60 61 return dst 62 } 63 64 // MarshalJSON implements encoding/json.Marshaler. 65 func (src NotificationResponse) MarshalJSON() ([]byte, error) { 66 return json.Marshal(struct { 67 Type string 68 PID uint32 69 Channel string 70 Payload string 71 }{ 72 Type: "NotificationResponse", 73 PID: src.PID, 74 Channel: src.Channel, 75 Payload: src.Payload, 76 }) 77 }