Newer
Older
package websocket
import (
"bufio"
"compress/flate"
"context"
"crypto/rand"
"encoding/binary"
"io"
"time"
)
// Writer returns a writer bounded by the context that will write
// a WebSocket message of type dataType to the connection.
//
// You must close the writer once you have written the entire message.
//
// Only one writer can be open at a time, multiple calls will block until the previous writer
// is closed.
//
// Never close the returned writer twice.
func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) {
return nil, xerrors.Errorf("failed to get writer: %w", err)
}
return w, nil
}
// Write writes a message to the connection.
//
// See the Writer method if you want to stream a message.
//
// If compression is disabled, then it is guaranteed to write the message
// in a single frame.
func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error {
func newMsgWriter(c *Conn) *msgWriter {
mw := &msgWriter{
c: c,
mu: newMu(c),
}
mw.trimWriter = &trimLastFourBytesWriter{
w: writerFunc(mw.write),
}
return mw
}
mw.flateWriter = getFlateWriter(mw.trimWriter, nil)
func (c *Conn) writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) {
err := c.msgWriter.reset(ctx, typ)
func (c *Conn) write(ctx context.Context, typ MessageType, p []byte) (int, error) {
mw, err := c.writer(ctx, typ)
return c.writeFrame(ctx, true, false, c.msgWriter.opcode, p)
trimWriter *trimLastFourBytesWriter
flateWriter *flate.Writer
func (mw *msgWriter) reset(ctx context.Context, typ MessageType) error {
err := mw.mu.Lock(ctx)
if err != nil {
return err
}
mw.closed = false
mw.ctx = ctx
mw.opcode = opcode(typ)
return nil
}
// Write writes the given bytes to the WebSocket connection.
func (mw *msgWriter) Write(p []byte) (_ int, err error) {
defer errd.Wrap(&err, "failed to write")
if mw.closed {
if mw.c.flate() {
if !mw.flate {
mw.flate = true
if !mw.flateContextTakeover() {
func (mw *msgWriter) write(p []byte) (int, error) {
n, err := mw.c.writeFrame(mw.ctx, false, mw.flate, mw.opcode, p)
return n, xerrors.Errorf("failed to write data frame: %w", err)
}
mw.opcode = opContinuation
return n, nil
}
// Close flushes the frame to the connection.
defer errd.Wrap(&err, "failed to close writer")
if mw.closed {
return xerrors.Errorf("failed to flush flate writer: %w", err)
_, err = mw.c.writeFrame(mw.ctx, true, mw.flate, mw.opcode, nil)
return xerrors.Errorf("failed to write fin frame: %w", err)
if mw.c.flate() && !mw.flateContextTakeover() && mw.flateWriter != nil {
mw.mu.Lock(context.Background())
putFlateWriter(mw.flateWriter)
}
}
func (c *Conn) writeControl(ctx context.Context, opcode opcode, p []byte) error {
ctx, cancel := context.WithTimeout(ctx, time.Second*5)
defer cancel()
return xerrors.Errorf("failed to write control frame %v: %w", opcode, err)
}
return nil
}
// frame handles all writes to the connection.
func (c *Conn) writeFrame(ctx context.Context, fin bool, flate bool, opcode opcode, p []byte) (int, error) {
case <-c.closed:
return 0, c.closeErr
case c.writeTimeout <- ctx:
c.writeHeader.fin = fin
c.writeHeader.opcode = opcode
c.writeHeader.payloadLength = int64(len(p))
if c.client {
c.writeHeader.masked = true
err = binary.Read(rand.Reader, binary.LittleEndian, &c.writeHeader.maskKey)
return 0, xerrors.Errorf("failed to generate masking key: %w", err)
if flate && (opcode == opText || opcode == opBinary) {
c.writeHeader.rsv1 = true
}
err = writeFrameHeader(c.writeHeader, c.bw)
case <-c.closed:
return n, c.closeErr
case c.writeTimeout <- context.Background():
func (c *Conn) writeFramePayload(p []byte) (_ int, err error) {
if !c.writeHeader.masked {
return c.bw.Write(p)
for len(p) > 0 {
// If the buffer is full, we need to flush.
if c.bw.Available() == 0 {
err = c.bw.Flush()
if err != nil {
return n, err
}
}
// Start of next write in the buffer.
if j > c.bw.Available() {
j = c.bw.Available()
maskKey = mask(maskKey, c.writeBuf[i:c.bw.Buffered()])
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
p = p[j:]
n += j
}
return n, nil
}
type writerFunc func(p []byte) (int, error)
func (f writerFunc) Write(p []byte) (int, error) {
return f(p)
}
// extractBufioWriterBuf grabs the []byte backing a *bufio.Writer
// and returns it.
func extractBufioWriterBuf(bw *bufio.Writer, w io.Writer) []byte {
var writeBuf []byte
bw.Reset(writerFunc(func(p2 []byte) (int, error) {
writeBuf = p2[:cap(p2)]
return len(p2), nil
}))
bw.WriteByte(0)
bw.Flush()
bw.Reset(w)
return writeBuf
}