...
1 package pgproto3
2
3 import (
4 "bytes"
5 "encoding/hex"
6 "encoding/json"
7 "errors"
8
9 "github.com/jackc/pgx/v5/internal/pgio"
10 )
11
12 type SASLInitialResponse struct {
13 AuthMechanism string
14 Data []byte
15 }
16
17
18 func (*SASLInitialResponse) Frontend() {}
19
20
21
22 func (dst *SASLInitialResponse) Decode(src []byte) error {
23 *dst = SASLInitialResponse{}
24
25 rp := 0
26
27 idx := bytes.IndexByte(src, 0)
28 if idx < 0 {
29 return errors.New("invalid SASLInitialResponse")
30 }
31
32 dst.AuthMechanism = string(src[rp:idx])
33 rp = idx + 1
34
35 rp += 4
36 dst.Data = src[rp:]
37
38 return nil
39 }
40
41
42 func (src *SASLInitialResponse) Encode(dst []byte) ([]byte, error) {
43 dst, sp := beginMessage(dst, 'p')
44
45 dst = append(dst, []byte(src.AuthMechanism)...)
46 dst = append(dst, 0)
47
48 dst = pgio.AppendInt32(dst, int32(len(src.Data)))
49 dst = append(dst, src.Data...)
50
51 return finishMessage(dst, sp)
52 }
53
54
55 func (src SASLInitialResponse) MarshalJSON() ([]byte, error) {
56 return json.Marshal(struct {
57 Type string
58 AuthMechanism string
59 Data string
60 }{
61 Type: "SASLInitialResponse",
62 AuthMechanism: src.AuthMechanism,
63 Data: string(src.Data),
64 })
65 }
66
67
68 func (dst *SASLInitialResponse) UnmarshalJSON(data []byte) error {
69
70 if string(data) == "null" {
71 return nil
72 }
73
74 var msg struct {
75 AuthMechanism string
76 Data string
77 }
78 if err := json.Unmarshal(data, &msg); err != nil {
79 return err
80 }
81 dst.AuthMechanism = msg.AuthMechanism
82 if msg.Data != "" {
83 decoded, err := hex.DecodeString(msg.Data)
84 if err != nil {
85 return err
86 }
87 dst.Data = decoded
88 }
89 return nil
90 }
91
View as plain text