sasl_response.go 1.3 KB

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