notification_response.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package pgproto3
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/json"
  6. "github.com/jackc/pgx/v5/internal/pgio"
  7. )
  8. type NotificationResponse struct {
  9. PID uint32
  10. Channel string
  11. Payload string
  12. }
  13. // Backend identifies this message as sendable by the PostgreSQL backend.
  14. func (*NotificationResponse) Backend() {}
  15. // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
  16. // type identifier and 4 byte message length.
  17. func (dst *NotificationResponse) Decode(src []byte) error {
  18. buf := bytes.NewBuffer(src)
  19. if buf.Len() < 4 {
  20. return &invalidMessageFormatErr{messageType: "NotificationResponse", details: "too short"}
  21. }
  22. pid := binary.BigEndian.Uint32(buf.Next(4))
  23. b, err := buf.ReadBytes(0)
  24. if err != nil {
  25. return err
  26. }
  27. channel := string(b[:len(b)-1])
  28. b, err = buf.ReadBytes(0)
  29. if err != nil {
  30. return err
  31. }
  32. payload := string(b[:len(b)-1])
  33. *dst = NotificationResponse{PID: pid, Channel: channel, Payload: payload}
  34. return nil
  35. }
  36. // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
  37. func (src *NotificationResponse) Encode(dst []byte) ([]byte, error) {
  38. dst, sp := beginMessage(dst, 'A')
  39. dst = pgio.AppendUint32(dst, src.PID)
  40. dst = append(dst, src.Channel...)
  41. dst = append(dst, 0)
  42. dst = append(dst, src.Payload...)
  43. dst = append(dst, 0)
  44. return finishMessage(dst, sp)
  45. }
  46. // MarshalJSON implements encoding/json.Marshaler.
  47. func (src NotificationResponse) MarshalJSON() ([]byte, error) {
  48. return json.Marshal(struct {
  49. Type string
  50. PID uint32
  51. Channel string
  52. Payload string
  53. }{
  54. Type: "NotificationResponse",
  55. PID: src.PID,
  56. Channel: src.Channel,
  57. Payload: src.Payload,
  58. })
  59. }