2019-09-23 12:18:00 +07:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2020-09-02 03:37:23 +07:00
|
|
|
"strconv"
|
2019-09-23 12:18:00 +07:00
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
2020-08-27 14:14:59 +07:00
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
ReadBufferSize: 1024,
|
|
|
|
WriteBufferSize: 1024,
|
|
|
|
}
|
2019-09-23 12:18:00 +07:00
|
|
|
|
|
|
|
func websocketConnection(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ws, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
2019-09-23 23:23:21 +07:00
|
|
|
_, _ = fmt.Fprint(w, "You must use the web socket protocol to connect to this endpoint.", err)
|
2019-09-23 12:18:00 +07:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer ws.Close()
|
|
|
|
|
|
|
|
for {
|
|
|
|
_, p, err := ws.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
handleDisconnection(ws)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
msg := string(p)
|
|
|
|
handleIncomingMessage(ws, msg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-02 03:37:23 +07:00
|
|
|
const port = 8080
|
|
|
|
|
2019-09-23 12:18:00 +07:00
|
|
|
func main() {
|
|
|
|
http.HandleFunc("/websocket", websocketConnection)
|
|
|
|
http.Handle("/", http.FileServer(http.Dir("./static")))
|
|
|
|
|
2020-09-02 03:37:23 +07:00
|
|
|
fmt.Println("Chat server opening on port", port)
|
|
|
|
err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
|
2019-09-26 00:42:13 +07:00
|
|
|
if err != nil {
|
2020-09-02 03:37:23 +07:00
|
|
|
_ = fmt.Errorf("Server could not start up: %s", err.Error())
|
2019-09-26 00:42:13 +07:00
|
|
|
}
|
2019-09-23 12:18:00 +07:00
|
|
|
}
|