davidnadejdin

Untitled

Jan 5th, 2022
2,907
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.07 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "flag"
  5.     "fmt"
  6.     "github.com/gorilla/websocket"
  7.     "log"
  8.     "net/http"
  9. )
  10.  
  11. var upgrader = websocket.Upgrader{
  12.     CheckOrigin: func(r *http.Request) bool {
  13.         return true
  14.     },
  15. }
  16. var addr = flag.String("addr", "localhost:8080", "http service address")
  17. var clients = make(map[*websocket.Conn]bool)
  18.  
  19. func main() {
  20.     flag.Parse()
  21.  
  22.     http.HandleFunc("/", echo)
  23.  
  24.     err := http.ListenAndServe(*addr, nil)
  25.  
  26.     if err != nil {
  27.         log.Println(err)
  28.     }
  29. }
  30.  
  31. func writeMessages(message *[]byte) {
  32.     for conn, active := range clients {
  33.         fmt.Println(active)
  34.         err := conn.WriteMessage(1, *message)
  35.  
  36.         if err != nil {
  37.             log.Println(err)
  38.         }
  39.     }
  40. }
  41.  
  42. func echo(w http.ResponseWriter, r *http.Request) {
  43.     conn, err := upgrader.Upgrade(w, r, nil)
  44.  
  45.     clients[conn] = true
  46.  
  47.     if err != nil {
  48.         log.Println(err)
  49.     }
  50.  
  51.     for {
  52.         mt, message, err := conn.ReadMessage()
  53.  
  54.         if err != nil || mt == websocket.CloseMessage {
  55.  
  56.             break
  57.         }
  58.  
  59.         go writeMessages(&message)
  60.     }
  61.  
  62.     delete(clients, conn)
  63.     err = conn.Close()
  64.  
  65.     if err != nil {
  66.         log.Println(err)
  67.     }
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment