wsutil.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. Package wsutil provides utilities for working with WebSocket protocol.
  3. Overview:
  4. // Read masked text message from peer and check utf8 encoding.
  5. header, err := ws.ReadHeader(conn)
  6. if err != nil {
  7. // handle err
  8. }
  9. // Prepare to read payload.
  10. r := io.LimitReader(conn, header.Length)
  11. r = wsutil.NewCipherReader(r, header.Mask)
  12. r = wsutil.NewUTF8Reader(r)
  13. payload, err := ioutil.ReadAll(r)
  14. if err != nil {
  15. // handle err
  16. }
  17. You could get the same behavior using just `wsutil.Reader`:
  18. r := wsutil.Reader{
  19. Source: conn,
  20. CheckUTF8: true,
  21. }
  22. payload, err := ioutil.ReadAll(r)
  23. if err != nil {
  24. // handle err
  25. }
  26. Or even simplest:
  27. payload, err := wsutil.ReadClientText(conn)
  28. if err != nil {
  29. // handle err
  30. }
  31. Package is also exports tools for buffered writing:
  32. // Create buffered writer, that will buffer output bytes and send them as
  33. // 128-length fragments (with exception on large writes, see the doc).
  34. writer := wsutil.NewWriterSize(conn, ws.StateServerSide, ws.OpText, 128)
  35. _, err := io.CopyN(writer, rand.Reader, 100)
  36. if err == nil {
  37. err = writer.Flush()
  38. }
  39. if err != nil {
  40. // handle error
  41. }
  42. For more utils and helpers see the documentation.
  43. */
  44. package wsutil