另客网go项目公用的代码库

json.go 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // One value is expected in the message.
  46. err = io.ErrUnexpectedEOF
  47. }
  48. return err
  49. }