json.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. "io"
  8. )
  9. // WriteJSON is deprecated, use c.WriteJSON instead.
  10. func WriteJSON(c *Conn, v interface{}) error {
  11. return c.WriteJSON(v)
  12. }
  13. // WriteJSON writes the JSON encoding of v to the connection.
  14. //
  15. // See the documentation for encoding/json Marshal for details about the
  16. // conversion of Go values to JSON.
  17. func (c *Conn) WriteJSON(v interface{}) error {
  18. w, err := c.NextWriter(TextMessage)
  19. if err != nil {
  20. return err
  21. }
  22. err1 := json.NewEncoder(w).Encode(v)
  23. err2 := w.Close()
  24. if err1 != nil {
  25. return err1
  26. }
  27. return err2
  28. }
  29. // ReadJSON is deprecated, use c.ReadJSON instead.
  30. func ReadJSON(c *Conn, v interface{}) error {
  31. return c.ReadJSON(v)
  32. }
  33. // ReadJSON reads the next JSON-encoded message from the connection and stores
  34. // it in the value pointed to by v.
  35. //
  36. // See the documentation for the encoding/json Unmarshal function for details
  37. // about the conversion of JSON to a Go value.
  38. func (c *Conn) ReadJSON(v interface{}) error {
  39. _, r, err := c.NextReader()
  40. if err != nil {
  41. return err
  42. }
  43. err = json.NewDecoder(r).Decode(v)
  44. if err == io.EOF {
  45. // Decode returns io.EOF when the message is empty or all whitespace.
  46. // Convert to io.ErrUnexpectedEOF so that application can distinguish
  47. // between an error reading the JSON value and the connection closing.
  48. err = io.ErrUnexpectedEOF
  49. }
  50. return err
  51. }