github.com/simonmittag/ws@v1.1.0-rc.5.0.20210419231947-82b846128245/doc.go (about) 1 /* 2 Package ws implements a client and server for the WebSocket protocol as 3 specified in RFC 6455. 4 5 The main purpose of this package is to provide simple low-level API for 6 efficient work with protocol. 7 8 Overview. 9 10 Upgrade to WebSocket (or WebSocket handshake) can be done in two ways. 11 12 The first way is to use `net/http` server: 13 14 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 15 conn, _, _, err := ws.UpgradeHTTP(r, w) 16 }) 17 18 The second and much more efficient way is so-called "zero-copy upgrade". It 19 avoids redundant allocations and copying of not used headers or other request 20 data. User decides by himself which data should be copied. 21 22 ln, err := net.Listen("tcp", ":8080") 23 if err != nil { 24 // handle error 25 } 26 27 conn, err := ln.Accept() 28 if err != nil { 29 // handle error 30 } 31 32 handshake, err := ws.Upgrade(conn) 33 if err != nil { 34 // handle error 35 } 36 37 For customization details see `ws.Upgrader` documentation. 38 39 After WebSocket handshake you can work with connection in multiple ways. 40 That is, `ws` does not force the only one way of how to work with WebSocket: 41 42 header, err := ws.ReadHeader(conn) 43 if err != nil { 44 // handle err 45 } 46 47 buf := make([]byte, header.Length) 48 _, err := io.ReadFull(conn, buf) 49 if err != nil { 50 // handle err 51 } 52 53 resp := ws.NewBinaryFrame([]byte("hello, world!")) 54 if err := ws.WriteFrame(conn, frame); err != nil { 55 // handle err 56 } 57 58 As you can see, it stream friendly: 59 60 const N = 42 61 62 ws.WriteHeader(ws.Header{ 63 Fin: true, 64 Length: N, 65 OpCode: ws.OpBinary, 66 }) 67 68 io.CopyN(conn, rand.Reader, N) 69 70 Or: 71 72 header, err := ws.ReadHeader(conn) 73 if err != nil { 74 // handle err 75 } 76 77 io.CopyN(ioutil.Discard, conn, header.Length) 78 79 For more info see the documentation. 80 */ 81 package ws