Skip to content

Instantly share code, notes, and snippets.

@cemdrk
Created January 17, 2020 13:48
Show Gist options
  • Save cemdrk/1202bb9b74353a9a92303b02d788156c to your computer and use it in GitHub Desktop.
Save cemdrk/1202bb9b74353a9a92303b02d788156c to your computer and use it in GitHub Desktop.
go websocket example
package main
import (
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
)
var clients = make(map[*websocket.Conn]bool)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/ws", wsHandler)
log.Fatal(http.ListenAndServe(":8000", router))
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
// register client
clients[ws] = true
log.Println(len(clients))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment