copy_data.go 1.4 KB

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