Skip to content

Instantly share code, notes, and snippets.

@quinn
Created April 24, 2018 00:26
Show Gist options
  • Save quinn/56f0d71cafeb407883a8387746727e35 to your computer and use it in GitHub Desktop.
Save quinn/56f0d71cafeb407883a8387746727e35 to your computer and use it in GitHub Desktop.
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var channels []chan []byte
func chat(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
defer c.Close()
myChan := make(chan []byte)
channels = append(channels, myChan)
myChanIndex := len(channels) - 1
defer func() {
log.Println("Disconnected. Removing channel...")
channels = append(channels[:myChanIndex], channels[myChanIndex+1:]...)
}()
// listen to our myChan for new messages
go func() {
for {
log.Println("waiting to receive from myChan")
message := <-myChan
log.Println("message received")
log.Println(string(message))
err = c.WriteMessage(websocket.TextMessage, message)
if err != nil {
log.Println("write:", err)
break
}
}
}()
if err != nil {
log.Print("upgrade:", err)
return
}
for {
log.Println("Waiting for message from reader")
_, message, err := c.ReadMessage()
if err != nil {
log.Println("ReadMessage failed")
return
} else {
log.Println("Sending messages")
for _, channel := range channels {
if channel != myChan {
channel <- message
}
}
}
}
}
func main() {
http.HandleFunc("/", chat)
log.Fatal(http.ListenAndServe("localhost:17777", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment