go-websockets-talk/code/main.go

51 lines
953 B
Go

package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var (
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
func websocketConnection(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Fprintf(w, "Internal server error: %s", err)
fmt.Printf("Internal server error: %s", err)
return
}
defer ws.Close()
ws.WriteMessage(websocket.TextMessage, []byte("nickname"))
for {
_, p, err := ws.ReadMessage()
if err != nil {
handleDisconnection(ws)
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}
msg := string(p)
handleIncomingMessage(ws, msg)
}
}
func main() {
http.HandleFunc("/websocket", websocketConnection)
http.Handle("/", http.FileServer(http.Dir("./static")))
http.ListenAndServe(":8080", nil)
}