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