khenaidoo | ab1f7bd | 2019-11-14 14:00:27 -0500 | [diff] [blame] | 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 | |
| 5 | package websocket |
| 6 | |
| 7 | import ( |
| 8 | "encoding/json" |
| 9 | "io" |
| 10 | ) |
| 11 | |
| 12 | // WriteJSON writes the JSON encoding of v as a message. |
| 13 | // |
| 14 | // Deprecated: Use c.WriteJSON instead. |
| 15 | func WriteJSON(c *Conn, v interface{}) error { |
| 16 | return c.WriteJSON(v) |
| 17 | } |
| 18 | |
| 19 | // WriteJSON writes the JSON encoding of v as a message. |
| 20 | // |
| 21 | // See the documentation for encoding/json Marshal for details about the |
| 22 | // conversion of Go values to JSON. |
| 23 | func (c *Conn) WriteJSON(v interface{}) error { |
| 24 | w, err := c.NextWriter(TextMessage) |
| 25 | if err != nil { |
| 26 | return err |
| 27 | } |
| 28 | err1 := json.NewEncoder(w).Encode(v) |
| 29 | err2 := w.Close() |
| 30 | if err1 != nil { |
| 31 | return err1 |
| 32 | } |
| 33 | return err2 |
| 34 | } |
| 35 | |
| 36 | // ReadJSON reads the next JSON-encoded message from the connection and stores |
| 37 | // it in the value pointed to by v. |
| 38 | // |
| 39 | // Deprecated: Use c.ReadJSON instead. |
| 40 | func ReadJSON(c *Conn, v interface{}) error { |
| 41 | return c.ReadJSON(v) |
| 42 | } |
| 43 | |
| 44 | // ReadJSON reads the next JSON-encoded message from the connection and stores |
| 45 | // it in the value pointed to by v. |
| 46 | // |
| 47 | // See the documentation for the encoding/json Unmarshal function for details |
| 48 | // about the conversion of JSON to a Go value. |
| 49 | func (c *Conn) ReadJSON(v interface{}) error { |
| 50 | _, r, err := c.NextReader() |
| 51 | if err != nil { |
| 52 | return err |
| 53 | } |
| 54 | err = json.NewDecoder(r).Decode(v) |
| 55 | if err == io.EOF { |
| 56 | // One value is expected in the message. |
| 57 | err = io.ErrUnexpectedEOF |
| 58 | } |
| 59 | return err |
| 60 | } |