Best K6 code snippet using ws.handleEvent
ws.go
Source:ws.go
...170 return nil, err171 }172 if connErr != nil {173 // Pass the error to the user script before exiting immediately174 socket.handleEvent("error", rt.ToValue(connErr))175 return nil, connErr176 }177 wsResponse, wsRespErr := wrapHTTPResponse(httpResponse)178 if wsRespErr != nil {179 return nil, wsRespErr180 }181 wsResponse.URL = url182 defer func() { _ = conn.Close() }()183 if state.Options.SystemTags["status"] {184 tags["status"] = strconv.Itoa(httpResponse.StatusCode)185 }186 if state.Options.SystemTags["subproto"] {187 tags["subproto"] = httpResponse.Header.Get("Sec-WebSocket-Protocol")188 }189 // The connection is now open, emit the event190 socket.handleEvent("open")191 // Pass ping/pong events through the main control loop192 pingChan := make(chan string)193 pongChan := make(chan string)194 conn.SetPingHandler(func(msg string) error { pingChan <- msg; return nil })195 conn.SetPongHandler(func(pingID string) error { pongChan <- pingID; return nil })196 readDataChan := make(chan []byte)197 readCloseChan := make(chan int)198 readErrChan := make(chan error)199 // Wraps a couple of channels around conn.ReadMessage200 go readPump(conn, readDataChan, readErrChan, readCloseChan)201 // This is the main control loop. All JS code (including error handlers)202 // should only be executed by this thread to avoid race conditions203 for {204 select {205 case pingData := <-pingChan:206 // Handle pings received from the server207 // - trigger the `ping` event208 // - reply with pong (needed when `SetPingHandler` is overwritten)209 err := socket.conn.WriteControl(websocket.PongMessage, []byte(pingData), time.Now().Add(writeWait))210 if err != nil {211 socket.handleEvent("error", rt.ToValue(err))212 }213 socket.handleEvent("ping")214 case pingID := <-pongChan:215 // Handle pong responses to our pings216 socket.trackPong(pingID)217 socket.handleEvent("pong")218 case readData := <-readDataChan:219 socket.msgReceivedTimestamps = append(socket.msgReceivedTimestamps, time.Now())220 socket.handleEvent("message", rt.ToValue(string(readData)))221 case readErr := <-readErrChan:222 socket.handleEvent("error", rt.ToValue(readErr))223 case readClose := <-readCloseChan:224 // handle server close225 socket.handleEvent("close", rt.ToValue(readClose))226 case scheduledFn := <-socket.scheduled:227 if _, err := scheduledFn(goja.Undefined()); err != nil {228 return nil, err229 }230 case <-ctx.Done():231 // VU is shutting down during an interrupt232 // socket events will not be forwarded to the VU233 _ = socket.closeConnection(websocket.CloseGoingAway)234 case <-socket.done:235 // This is the final exit point normally triggered by closeConnection236 end := time.Now()237 sessionDuration := stats.D(end.Sub(start))238 sampleTags := stats.IntoSampleTags(&tags)239 stats.PushIfNotCancelled(ctx, state.Samples, stats.ConnectedSamples{240 Samples: []stats.Sample{241 {Metric: metrics.WSSessions, Time: start, Tags: sampleTags, Value: 1},242 {Metric: metrics.WSConnecting, Time: start, Tags: sampleTags, Value: connectionDuration},243 {Metric: metrics.WSSessionDuration, Time: start, Tags: sampleTags, Value: sessionDuration},244 },245 Tags: sampleTags,246 Time: start,247 })248 for _, msgSentTimestamp := range socket.msgSentTimestamps {249 stats.PushIfNotCancelled(ctx, state.Samples, stats.Sample{250 Metric: metrics.WSMessagesSent,251 Time: msgSentTimestamp,252 Tags: sampleTags,253 Value: 1,254 })255 }256 for _, msgReceivedTimestamp := range socket.msgReceivedTimestamps {257 stats.PushIfNotCancelled(ctx, state.Samples, stats.Sample{258 Metric: metrics.WSMessagesReceived,259 Time: msgReceivedTimestamp,260 Tags: sampleTags,261 Value: 1,262 })263 }264 for _, pingDelta := range socket.pingTimestamps {265 stats.PushIfNotCancelled(ctx, state.Samples, stats.Sample{266 Metric: metrics.WSPing,267 Time: pingDelta.pong,268 Tags: sampleTags,269 Value: stats.D(pingDelta.pong.Sub(pingDelta.ping)),270 })271 }272 return wsResponse, nil273 }274 }275}276func (s *Socket) On(event string, handler goja.Value) {277 if handler, ok := goja.AssertFunction(handler); ok {278 s.eventHandlers[event] = append(s.eventHandlers[event], handler)279 }280}281func (s *Socket) handleEvent(event string, args ...goja.Value) {282 if handlers, ok := s.eventHandlers[event]; ok {283 for _, handler := range handlers {284 if _, err := handler(goja.Undefined(), args...); err != nil {285 common.Throw(common.GetRuntime(s.ctx), err)286 }287 }288 }289}290func (s *Socket) Send(message string) {291 // NOTE: No binary message support for the time being since goja doesn't292 // support typed arrays.293 rt := common.GetRuntime(s.ctx)294 writeData := []byte(message)295 if err := s.conn.WriteMessage(websocket.TextMessage, writeData); err != nil {296 s.handleEvent("error", rt.ToValue(err))297 }298 s.msgSentTimestamps = append(s.msgSentTimestamps, time.Now())299}300func (s *Socket) Ping() {301 rt := common.GetRuntime(s.ctx)302 deadline := time.Now().Add(writeWait)303 pingID := strconv.Itoa(s.pingSendCounter)304 data := []byte(pingID)305 err := s.conn.WriteControl(websocket.PingMessage, data, deadline)306 if err != nil {307 s.handleEvent("error", rt.ToValue(err))308 return309 }310 s.pingSendTimestamps[pingID] = time.Now()311 s.pingSendCounter++312}313func (s *Socket) trackPong(pingID string) {314 pongTimestamp := time.Now()315 if _, ok := s.pingSendTimestamps[pingID]; !ok {316 // We received a pong for a ping we didn't send; ignore317 // (this shouldn't happen with a compliant server)318 return319 }320 pingTimestamp := s.pingSendTimestamps[pingID]321 s.pingTimestamps = append(s.pingTimestamps, pingDelta{pingTimestamp, pongTimestamp})322}323func (s *Socket) SetTimeout(fn goja.Callable, timeoutMs int) {324 // Starts a goroutine, blocks once on the timeout and pushes the callable325 // back to the main loop through the scheduled channel326 go func() {327 select {328 case <-time.After(time.Duration(timeoutMs) * time.Millisecond):329 s.scheduled <- fn330 case <-s.done:331 return332 }333 }()334}335func (s *Socket) SetInterval(fn goja.Callable, intervalMs int) {336 // Starts a goroutine, blocks forever on the ticker and pushes the callable337 // back to the main loop through the scheduled channel338 go func() {339 ticker := time.NewTicker(time.Duration(intervalMs) * time.Millisecond)340 defer ticker.Stop()341 for {342 select {343 case <-ticker.C:344 s.scheduled <- fn345 case <-s.done:346 return347 }348 }349 }()350}351func (s *Socket) Close(args ...goja.Value) {352 code := websocket.CloseGoingAway353 if len(args) > 0 {354 code = int(args[0].ToInteger())355 }356 _ = s.closeConnection(code)357}358// Attempts to close the websocket gracefully359func (s *Socket) closeConnection(code int) error {360 var err error361 s.shutdownOnce.Do(func() {362 rt := common.GetRuntime(s.ctx)363 writeErr := s.conn.WriteControl(websocket.CloseMessage,364 websocket.FormatCloseMessage(code, ""),365 time.Now().Add(writeWait),366 )367 if writeErr != nil {368 // Just call the handler, we'll try to close the connection anyway369 s.handleEvent("error", rt.ToValue(err))370 err = writeErr371 }372 // trigger `close` event when the client closes the connection373 s.handleEvent("close", rt.ToValue(code))374 _ = s.conn.Close()375 // Stops the main control loop376 close(s.done)377 })378 return err379}380// Wraps conn.ReadMessage in a channel381func readPump(conn *websocket.Conn, readChan chan []byte, errorChan chan error, closeChan chan int) {382 defer func() { _ = conn.Close() }()383 for {384 _, message, err := conn.ReadMessage()385 if err != nil {386 if websocket.IsCloseError(err, websocket.CloseNormalClosure) {387 closeChan <- err.(*websocket.CloseError).Code...
widget.go
Source:widget.go
1package rat2type Widget interface {3 SetBox(Box)4 GetBox() Box5 Render()6 HandleEvent([]keyEvent) bool7 Destroy()8}9type WidgetStack interface {10 Widget11 Push(w Widget)12 Pop() Widget13 Size() int14}15type widgetStack struct {16 lastEl *widgetStackElement17 box Box18 size int19}20type widgetStackElement struct {21 widget Widget22 previous *widgetStackElement23}24func NewWidgetStack() WidgetStack {25 return &widgetStack{}26}27func (ws *widgetStack) Push(w Widget) {28 ws.lastEl = &widgetStackElement{w, ws.lastEl}29 ws.size++30 ws.layout()31}32func (ws *widgetStack) Pop() Widget {33 if ws.lastEl == nil {34 return nil35 }36 w := ws.lastEl.widget37 ws.lastEl = ws.lastEl.previous38 ws.size--39 w.Destroy()40 return w41}42func (ws *widgetStack) Size() int {43 return ws.size44}45func (ws *widgetStack) SetBox(b Box) {46 ws.box = b47 ws.layout()48}49func (ws *widgetStack) GetBox() Box {50 return ws.box51}52func (ws *widgetStack) Render() {53 if ws.lastEl != nil {54 ws.lastEl.widget.Render()55 }56}57func (ws *widgetStack) HandleEvent(ks []keyEvent) bool {58 return ws.lastEl.widget.HandleEvent(ks)59}60func (ws *widgetStack) Destroy() {61 for ws.size > 0 {62 ws.Pop()63 }64}65func (ws *widgetStack) layout() {66 for e := ws.lastEl; e != nil; e = e.previous {67 e.widget.SetBox(ws.box)68 }69}...
handleEvent
Using AI Code Generation
1import (2var upgrader = websocket.Upgrader{3}4type ws struct {5 userData map[string]interface{}6}7func (w *ws) reader() {8 for {9 if _, msg, err := w.socket.ReadMessage(); err == nil {10 fmt.Println(string(msg))11 } else {12 }13 }14 w.socket.Close()15}16func (w *ws) writer() {17 for msg := range w.send {18 if err := w.socket.WriteMessage(websocket.TextMessage, msg); err != nil {19 }20 }21 w.socket.Close()22}23func (w *ws) serverHTTP(rw http.ResponseWriter, r *http.Request) {24 socket, err := upgrader.Upgrade(rw, r, nil)25 if err != nil {26 fmt.Println("Error upgrading get request to websocket:", err)27 }28 w = &ws{socket: socket, send: make(chan []byte, 256), room: w.room, userData: make(map[string]interface{})}29 defer func() { w.room.leave <- w }()30 go w.writer()31 w.reader()32}33func (w *ws) handleEvent(event string, data interface{}) {34 switch event {35 w.room.forward <- []byte(data.(string))36 w.room.forward <- []byte(fmt.Sprintf("%s has changed their name to %s", w.userData["id"], data))37 }38}39func (w *ws) notifyMeAbout(event string) {40 message := make(map[string]interface{})41 w.send <- []byte(message)42}43func (w *ws) notifyAboutJoin() {44 message := make(map[string]interface
handleEvent
Using AI Code Generation
1import (2var upgrader = websocket.Upgrader{3}4type Ws struct {5}6func (ws *Ws) handleEvent() {7 for {8 _, msg, err := ws.Conn.ReadMessage()9 if err != nil {10 log.Println(err)11 }12 log.Println(string(msg))13 }14}15func main() {16 http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {17 conn, err := upgrader.Upgrade(w, r, nil)18 if err != nil {19 log.Println(err)20 }21 ws := &Ws{Conn: conn}22 go ws.handleEvent()23 })24 server := &http.Server{25 }26 fmt.Println("Listening on port 8080")27 log.Fatal(server.ListenAndServe())28}
handleEvent
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", handleEvent)4 http.ListenAndServe(":8080", nil)5}6func handleEvent(w http.ResponseWriter, r *http.Request) {7 fmt.Println("Client connected")8 conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024)9 for {10 messageType, p, _ := conn.ReadMessage()11 fmt.Println(string(p))12 if err := conn.WriteMessage(messageType, p); err != nil {13 }14 }15}
handleEvent
Using AI Code Generation
1import (2var upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {3}}4func main() {5 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {6 fmt.Println("Request received")7 if err != nil {8 fmt.Println("Error in upgrading connection")9 }10 fmt.Println("Connection upgraded")11 for {12 messageType, p, err := conn.ReadMessage()13 if err != nil {14 fmt.Println("Error in reading message")15 }16 fmt.Println("Message received from browser")17 fmt.Println("Message type: ", messageType)18 fmt.Println("Message: ", string(p))19 if err = conn.WriteMessage(messageType, p); err != nil {20 fmt.Println("Error in writing message")21 }22 fmt.Println("Message written back to browser")23 }24 })25 http.ListenAndServe(":8080", nil)26}
handleEvent
Using AI Code Generation
1import (2var (3 upgrader = websocket.Upgrader{4 }5func handleEvent(w http.ResponseWriter, r *http.Request) {6 conn, err := upgrader.Upgrade(w, r, nil)7 if err != nil {8 log.Fatal("Error upgrading to websocket: ", err)9 }10 defer conn.Close()11 for {12 msgType, msg, err := conn.ReadMessage()13 if err != nil {14 log.Fatal("Error reading message: ", err)15 }16 fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))17 if err := conn.WriteMessage(msgType, msg); err != nil {18 log.Fatal("Error writing message: ", err)19 }20 }21}22func main() {23 fs := http.FileServer(http.Dir("../public"))24 http.Handle("/", fs)25 http.HandleFunc("/ws", handleEvent)26 log.Println("Starting server on :8080")27 go func() {28 time.Sleep(10 * time.Second)29 }()30 err := http.ListenAndServe(":8080", nil)31 if err != nil {32 log.Fatal("Error starting server: ", err)33 }34}
handleEvent
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", handleEvent)4 http.ListenAndServe(":8080", nil)5}6func handleEvent(w http.ResponseWriter, r *http.Request) {7 var upgrader = websocket.Upgrader{8 }9 conn, err := upgrader.Upgrade(w, r, nil)10 if err != nil {11 fmt.Println("Error in upgrading the request to websocket")12 }13 for {14 msgType, msg, err := conn.ReadMessage()15 if err != nil {16 fmt.Println("Error in reading the msg from client")17 }18 fmt.Println("msg from client:", string(msg))19 err = conn.WriteMessage(msgType, msg)20 if err != nil {21 fmt.Println("Error in writing the msg to client")22 }23 time.Sleep(time.Second * 1)24 }25}
handleEvent
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 ws, err := upgrader.Upgrade(w, r, nil)5 if err != nil {6 log.Println(err)7 }8 for {9 err := ws.ReadJSON(&msg)10 if err != nil {11 log.Println(err)12 }13 fmt.Println(msg)14 }15 })16 http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {17 ws, err := upgrader.Upgrade(w, r, nil)18 ws.SetCloseHandler(func(code int, text string) error {19 fmt.Println("close code:", code, "text:", text)20 })21 ws.SetPingHandler(func(appData string) error {22 fmt.Println("ping:", appData)23 })24 ws.SetPongHandler(func(appData string) error {25 fmt.Println("pong:", appData)26 })27 if err != nil {28 log.Println(err)29 }30 for {31 err := ws.ReadJSON(&msg)32 if err != nil {33 log.Println(err)34 }35 fmt.Println(msg)36 err = ws.WriteJSON(msg)37 if err != nil {38 log.Println(err)39 }40 }41 })42 http.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {43 ws, err := upgrader.Upgrade(w, r, nil)44 ws.SetCloseHandler(func(code int, text string) error {45 fmt.Println("close code:", code, "text:", text)46 })47 ws.SetPingHandler(func(appData string) error {48 fmt.Println("ping:", appData)49 })50 ws.SetPongHandler(func(appData string) error {51 fmt.Println("pong:", appData)
handleEvent
Using AI Code Generation
1import (2func handleEvent() {3 _, message, err := ws.ReadMessage()4 if err != nil {5 fmt.Println("error")6 }7 fmt.Println(string(message))8}9func main() {10 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {11 ws, err = websocket.Upgrade(w, r, nil, 1024, 1024)12 if err != nil {13 fmt.Println("error")14 }15 handleEvent()16 })17 http.ListenAndServe(":8080", nil)18}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!