Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "flag"
- "fmt"
- "github.com/gorilla/websocket"
- "log"
- "net/http"
- )
- var upgrader = websocket.Upgrader{
- CheckOrigin: func(r *http.Request) bool {
- return true
- },
- }
- var addr = flag.String("addr", "localhost:8080", "http service address")
- var clients = make(map[*websocket.Conn]bool)
- func main() {
- flag.Parse()
- http.HandleFunc("/", echo)
- err := http.ListenAndServe(*addr, nil)
- if err != nil {
- log.Println(err)
- }
- }
- func writeMessages(message *[]byte) {
- for conn, active := range clients {
- fmt.Println(active)
- err := conn.WriteMessage(1, *message)
- if err != nil {
- log.Println(err)
- }
- }
- }
- func echo(w http.ResponseWriter, r *http.Request) {
- conn, err := upgrader.Upgrade(w, r, nil)
- clients[conn] = true
- if err != nil {
- log.Println(err)
- }
- for {
- mt, message, err := conn.ReadMessage()
- if err != nil || mt == websocket.CloseMessage {
- break
- }
- go writeMessages(&message)
- }
- delete(clients, conn)
- err = conn.Close()
- if err != nil {
- log.Println(err)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment