1// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package websocket
6
7import (
8 "encoding/json"
9 "io"
10)
11
12// WriteJSON is deprecated, use c.WriteJSON instead.
13func WriteJSON(c *Conn, v interface{}) error {
14 return c.WriteJSON(v)
15}
16
17// WriteJSON writes the JSON encoding of v to the connection.
18//
19// See the documentation for encoding/json Marshal for details about the
20// conversion of Go values to JSON.
21func (c *Conn) WriteJSON(v interface{}) error {
22 w, err := c.NextWriter(TextMessage)
23 if err != nil {
24 return err
25 }
26 err1 := json.NewEncoder(w).Encode(v)
27 err2 := w.Close()
28 if err1 != nil {
29 return err1
30 }
31 return err2
32}
33
34// ReadJSON is deprecated, use c.ReadJSON instead.
35func ReadJSON(c *Conn, v interface{}) error {
36 return c.ReadJSON(v)
37}
38
39// ReadJSON reads the next JSON-encoded message from the connection and stores
40// it in the value pointed to by v.
41//
42// See the documentation for the encoding/json Unmarshal function for details
43// about the conversion of JSON to a Go value.
44func (c *Conn) ReadJSON(v interface{}) error {
45 _, r, err := c.NextReader()
46 if err != nil {
47 return err
48 }
49 err = json.NewDecoder(r).Decode(v)
50 if err == io.EOF {
51 // One value is expected in the message.
52 err = io.ErrUnexpectedEOF
53 }
54 return err
55}