json.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. package websocket
  5. import (
  6. "encoding/json"
  7. )
  8. // WriteJSON is deprecated, use c.WriteJSON instead.
  9. func WriteJSON(c *Conn, v interface{}) error {
  10. return c.WriteJSON(v)
  11. }
  12. // WriteJSON writes the JSON encoding of v to the connection.
  13. //
  14. // See the documentation for encoding/json Marshal for details about the
  15. // conversion of Go values to JSON.
  16. func (c *Conn) WriteJSON(v interface{}) error {
  17. w, err := c.NextWriter(TextMessage)
  18. if err != nil {
  19. return err
  20. }
  21. err1 := json.NewEncoder(w).Encode(v)
  22. err2 := w.Close()
  23. if err1 != nil {
  24. return err1
  25. }
  26. return err2
  27. }
  28. // ReadJSON is deprecated, use c.ReadJSON instead.
  29. func ReadJSON(c *Conn, v interface{}) error {
  30. return c.ReadJSON(v)
  31. }
  32. // ReadJSON reads the next JSON-encoded message from the connection and stores
  33. // it in the value pointed to by v.
  34. //
  35. // See the documentation for the encoding/json Marshal function for details
  36. // about the conversion of JSON to a Go value.
  37. func (c *Conn) ReadJSON(v interface{}) error {
  38. _, r, err := c.NextReader()
  39. if err != nil {
  40. return err
  41. }
  42. return json.NewDecoder(r).Decode(v)
  43. }