2020-10-20 15:26:55 +00:00
|
|
|
/*
|
|
|
|
Package wsutil provides utilities for working with WebSocket protocol.
|
|
|
|
|
|
|
|
Overview:
|
|
|
|
|
2024-10-17 20:09:39 +00:00
|
|
|
// Read masked text message from peer and check utf8 encoding.
|
|
|
|
header, err := ws.ReadHeader(conn)
|
|
|
|
if err != nil {
|
|
|
|
// handle err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Prepare to read payload.
|
|
|
|
r := io.LimitReader(conn, header.Length)
|
|
|
|
r = wsutil.NewCipherReader(r, header.Mask)
|
|
|
|
r = wsutil.NewUTF8Reader(r)
|
|
|
|
|
|
|
|
payload, err := ioutil.ReadAll(r)
|
|
|
|
if err != nil {
|
|
|
|
// handle err
|
|
|
|
}
|
2020-10-20 15:26:55 +00:00
|
|
|
|
|
|
|
You could get the same behavior using just `wsutil.Reader`:
|
|
|
|
|
2024-10-17 20:09:39 +00:00
|
|
|
r := wsutil.Reader{
|
|
|
|
Source: conn,
|
|
|
|
CheckUTF8: true,
|
|
|
|
}
|
2020-10-20 15:26:55 +00:00
|
|
|
|
2024-10-17 20:09:39 +00:00
|
|
|
payload, err := ioutil.ReadAll(r)
|
|
|
|
if err != nil {
|
|
|
|
// handle err
|
|
|
|
}
|
2020-10-20 15:26:55 +00:00
|
|
|
|
|
|
|
Or even simplest:
|
|
|
|
|
2024-10-17 20:09:39 +00:00
|
|
|
payload, err := wsutil.ReadClientText(conn)
|
|
|
|
if err != nil {
|
|
|
|
// handle err
|
|
|
|
}
|
2020-10-20 15:26:55 +00:00
|
|
|
|
|
|
|
Package is also exports tools for buffered writing:
|
|
|
|
|
2024-10-17 20:09:39 +00:00
|
|
|
// Create buffered writer, that will buffer output bytes and send them as
|
|
|
|
// 128-length fragments (with exception on large writes, see the doc).
|
|
|
|
writer := wsutil.NewWriterSize(conn, ws.StateServerSide, ws.OpText, 128)
|
|
|
|
|
|
|
|
_, err := io.CopyN(writer, rand.Reader, 100)
|
|
|
|
if err == nil {
|
|
|
|
err = writer.Flush()
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
// handle error
|
|
|
|
}
|
2020-10-20 15:26:55 +00:00
|
|
|
|
|
|
|
For more utils and helpers see the documentation.
|
|
|
|
*/
|
|
|
|
package wsutil
|