Created
January 17, 2020 13:48
-
-
Save cemdrk/1202bb9b74353a9a92303b02d788156c to your computer and use it in GitHub Desktop.
go websocket example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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