server-go/socket/conn-json.go

56 lines
1.4 KiB
Go
Raw Normal View History

2018-04-04 04:01:26 +00:00
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2018-04-05 15:15:29 +00:00
package socket
2018-04-04 04:01:26 +00:00
import (
"encoding/json"
"io"
)
// WriteJSON is deprecated, use c.WriteJSON instead.
2018-04-04 16:51:34 +00:00
func WriteJSON(c *SocketConn, v interface{}) error {
2018-04-04 04:01:26 +00:00
return c.WriteJSON(v)
}
// WriteJSON writes the JSON encoding of v to the connection.
//
// See the documentation for encoding/json Marshal for details about the
// conversion of Go values to JSON.
2018-04-04 16:51:34 +00:00
func (c *SocketConn) WriteJSON(v interface{}) error {
2018-06-29 08:53:39 +00:00
w, err := c.NextWriter(TextMessage)
2018-04-04 04:01:26 +00:00
if err != nil {
return err
}
err1 := json.NewEncoder(w).Encode(v)
err2 := w.Close()
if err1 != nil {
return err1
}
return err2
}
// ReadJSON is deprecated, use c.ReadJSON instead.
2018-04-04 16:51:34 +00:00
func ReadJSON(c *SocketConn, v interface{}) error {
2018-04-04 04:01:26 +00:00
return c.ReadJSON(v)
}
// ReadJSON reads the next JSON-encoded message from the connection and stores
// it in the value pointed to by v.
//
// See the documentation for the encoding/json Unmarshal function for details
// about the conversion of JSON to a Go value.
2018-04-04 16:51:34 +00:00
func (c *SocketConn) ReadJSON(v interface{}) error {
2018-04-04 04:01:26 +00:00
_, r, err := c.NextReader()
if err != nil {
return err
}
err = json.NewDecoder(r).Decode(v)
if err == io.EOF {
// One value is expected in the message.
err = io.ErrUnexpectedEOF
}
return err
}