github.com/simonmittag/ws@v1.1.0-rc.5.0.20210419231947-82b846128245/wsutil/wsutil.go (about)

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