get rid of WriteJSON() and replace calls with manually marshaled envelopes.

This commit is contained in:
fiatjaf
2023-05-09 17:02:22 -03:00
parent d36fbb95b9
commit ccbb44989f
4 changed files with 46 additions and 50 deletions

View File

@ -32,6 +32,9 @@ func ParseMessage(message []byte) Envelope {
v = &OKEnvelope{}
case bytes.Contains(label, []byte("AUTH")):
v = &AuthEnvelope{}
case bytes.Contains(label, []byte("CLOSE")):
x := CloseEnvelope("")
v = &x
}
if err := v.UnmarshalJSON(message); err != nil {
@ -56,6 +59,7 @@ var (
_ Envelope = (*ReqEnvelope)(nil)
_ Envelope = (*NoticeEnvelope)(nil)
_ Envelope = (*EOSEEnvelope)(nil)
_ Envelope = (*CloseEnvelope)(nil)
_ Envelope = (*OKEnvelope)(nil)
_ Envelope = (*AuthEnvelope)(nil)
)
@ -173,6 +177,30 @@ func (v EOSEEnvelope) MarshalJSON() ([]byte, error) {
return w.BuildBytes()
}
type CloseEnvelope string
func (_ CloseEnvelope) Label() string { return "CLOSE" }
func (v *CloseEnvelope) UnmarshalJSON(data []byte) error {
r := gjson.ParseBytes(data)
arr := r.Array()
switch len(arr) {
case 2:
*v = CloseEnvelope(arr[1].Str)
return nil
default:
return fmt.Errorf("failed to decode CLOSE envelope")
}
}
func (v CloseEnvelope) MarshalJSON() ([]byte, error) {
w := jwriter.Writer{}
w.RawString(`["CLOSE",`)
w.Raw(json.Marshal(string(v)))
w.RawString(`]`)
return w.BuildBytes()
}
type OKEnvelope struct {
EventID string
OK bool