json.go 990 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Copyright 2013 Gary Burd. 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 writes the JSON encoding of v to the connection.
  9. //
  10. // See the documentation for encoding/json Marshal for details about the
  11. // conversion of Go values to JSON.
  12. func WriteJSON(c *Conn, v interface{}) error {
  13. w, err := c.NextWriter(TextMessage)
  14. if err != nil {
  15. return err
  16. }
  17. err1 := json.NewEncoder(w).Encode(v)
  18. err2 := w.Close()
  19. if err1 != nil {
  20. return err1
  21. }
  22. return err2
  23. }
  24. // ReadJSON reads the next JSON-encoded message from the connection and stores
  25. // it in the value pointed to by v.
  26. //
  27. // See the documentation for the encoding/json Marshal function for details
  28. // about the conversion of JSON to a Go value.
  29. func ReadJSON(c *Conn, v interface{}) error {
  30. _, r, err := c.NextReader()
  31. if err != nil {
  32. return err
  33. }
  34. return json.NewDecoder(r).Decode(v)
  35. }