main.go 964 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package main
  2. import (
  3. "fmt"
  4. // "io"
  5. "log"
  6. "net/http"
  7. // "github.com/gorilla/websocket"
  8. )
  9. func homePage(w http.ResponseWriter, r *http.Request) {
  10. fmt.Fprintf(w, "Home Page")
  11. }
  12. func serveWs(pool *Pool, w http.ResponseWriter, r *http.Request) {
  13. fmt.Println("WebSocket Endpoint Hit")
  14. conn, err := Upgrade(w, r)
  15. if err != nil {
  16. fmt.Fprintf(w, "%+v\n", err)
  17. }
  18. if (conn == nil) {
  19. log.Println("Client not using websocket protocol")
  20. fmt.Fprintf(w, "%+v\n", err)
  21. return
  22. }
  23. client := &Client{
  24. Conn: conn,
  25. Pool: pool,
  26. }
  27. pool.Register <- client
  28. client.Read()
  29. }
  30. func setupRoutes() {
  31. http.HandleFunc("/", homePage)
  32. pool := NewPool()
  33. go pool.Start()
  34. http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
  35. serveWs(pool, w, r)
  36. })
  37. }
  38. func main() {
  39. fmt.Println("Distributed Chat App v0.01")
  40. setupRoutes()
  41. log.Fatal(http.ListenAndServe(":8008", nil))
  42. }