MCPcopy
hub / github.com/coder/websocket / Example_writeOnly

Function Example_writeOnly

example_test.go:82–118  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

80}
81
82func Example_writeOnly() {
83 // This handler demonstrates how to correctly handle a write only WebSocket connection.
84 // i.e you only expect to write messages and do not expect to read any messages.
85 fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
86 c, err := websocket.Accept(w, r, nil)
87 if err != nil {
88 log.Println(err)
89 return
90 }
91 defer c.CloseNow()
92
93 ctx, cancel := context.WithTimeout(r.Context(), time.Minute*10)
94 defer cancel()
95
96 ctx = c.CloseRead(ctx)
97
98 t := time.NewTicker(time.Second * 30)
99 defer t.Stop()
100
101 for {
102 select {
103 case <-ctx.Done():
104 c.Close(websocket.StatusNormalClosure, "")
105 return
106 case <-t.C:
107 err = wsjson.Write(ctx, c, "hi")
108 if err != nil {
109 log.Println(err)
110 return
111 }
112 }
113 }
114 })
115
116 err := http.ListenAndServe("localhost:8080", fn)
117 log.Fatal(err)
118}
119
120func Example_crossOrigin() {
121 // This handler demonstrates how to safely accept cross origin WebSockets

Callers

nothing calls this directly

Calls 5

AcceptFunction · 0.92
WriteFunction · 0.92
CloseNowMethod · 0.45
CloseReadMethod · 0.45
CloseMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…