tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/net/websocket/handler/main.go (about) 1 // This example is a websocket server. It listens for websocket clients 2 // to connect and echos messages back to the client. For client, see 3 // 4 // https://pkg.go.dev/golang.org/x/net/websocket#example-Dial 5 // 6 // Note: It may be necessary to increase the stack size when using 7 // "golang.org/x/net/websocket". Use the -stack-size=4KB command line option. 8 9 //go:build ninafw || wioterminal 10 11 package main 12 13 import ( 14 "io" 15 "log" 16 "machine" 17 "net/http" 18 "time" 19 20 "golang.org/x/net/websocket" 21 "tinygo.org/x/drivers/netlink" 22 "tinygo.org/x/drivers/netlink/probe" 23 ) 24 25 var ( 26 ssid string 27 pass string 28 port string = ":8080" 29 ) 30 31 // Echo the data received on the WebSocket. 32 func EchoServer(ws *websocket.Conn) { 33 io.Copy(ws, ws) 34 } 35 36 // Wait for user to open serial console 37 func waitSerial() { 38 for !machine.Serial.DTR() { 39 time.Sleep(100 * time.Millisecond) 40 } 41 } 42 43 // This example demonstrates a trivial echo server. 44 func main() { 45 waitSerial() 46 47 link, _ := probe.Probe() 48 49 err := link.NetConnect(&netlink.ConnectParams{ 50 Ssid: ssid, 51 Passphrase: pass, 52 }) 53 if err != nil { 54 log.Fatal(err) 55 } 56 57 http.Handle("/echo", websocket.Handler(EchoServer)) 58 err = http.ListenAndServe(port, nil) 59 if err != nil { 60 panic("ListenAndServe: " + err.Error()) 61 } 62 }