github.com/anycable/anycable-go@v1.5.1/encoders/json.go (about) 1 package encoders 2 3 import ( 4 "encoding/json" 5 6 "github.com/anycable/anycable-go/common" 7 "github.com/anycable/anycable-go/ws" 8 ) 9 10 const jsonEncoderID = "json" 11 12 type JSON struct { 13 } 14 15 func (JSON) ID() string { 16 return jsonEncoderID 17 } 18 19 func (JSON) Encode(msg EncodedMessage) (*ws.SentFrame, error) { 20 b, err := json.Marshal(&msg) 21 if err != nil { 22 panic("Failed to build JSON 😲") 23 } 24 return &ws.SentFrame{FrameType: ws.TextFrame, Payload: b}, nil 25 } 26 27 func (JSON) EncodeTransmission(msg string) (*ws.SentFrame, error) { 28 return &ws.SentFrame{FrameType: ws.TextFrame, Payload: []byte(msg)}, nil 29 } 30 31 func (JSON) Decode(raw []byte) (*common.Message, error) { 32 msg := &common.Message{} 33 34 if err := json.Unmarshal(raw, &msg); err != nil { 35 return nil, err 36 } 37 38 return msg, nil 39 }