53/100 Dias de Golang - Websockets com Melody
Table of Contents
#
Websockets com Melody
WebSockets são uma tecnologia essencial para aplicações que exigem comunicação bidirecional em tempo real, como chats, dashboards, jogos e sistemas colaborativos. Encontrei essa lib chamada Melody. Vamos construir um mesmo chat de mensagens só que agora com uma interface web. Esse exemplo está na documentação da biblioteca.
package main
import (
"net/http"
"github.com/olahol/melody"
)
func main() {
m := melody.New()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
m.HandleRequest(w, r)
})
m.HandleMessage(func(s *melody.Session, msg []byte) {
m.Broadcast(msg)
})
http.ListenAndServe(":5000", nil)
}
Na mesma pasta do projeto adicione um index.html
<html>
<head>
<title>Melody example: chatting</title>
</head>
<style>
#chat {
text-align: left;
background: #f1f1f1;
width: 500px;
min-height: 300px;
padding: 20px;
}
</style>
<body>
<center>
<h3>Chat</h3>
<pre id="chat"></pre>
<input placeholder="say something" id="text" type="text">
</center>
<script>
var url = "ws://" + window.location.host + "/ws";
var ws = new WebSocket(url);
var name = "Guest" + Math.floor(Math.random() * 1000);
var chat = document.getElementById("chat");
var text = document.getElementById("text");
var now = function () {
var iso = new Date().toISOString();
return iso.split("T")[1].split(".")[0];
};
ws.onmessage = function (msg) {
var line = now() + " " + msg.data + "\n";
chat.innerText += line;
};
text.onkeydown = function (e) {
if (e.keyCode === 13 && text.value !== "") {
ws.send("<" + name + "> " + text.value);
text.value = "";
}
};
</script>
</body>
</html>
Para iniciar o projet:
go mod init
e para instalar as libs:
go mod tidy
Veja a facilidade de fazer o chat com a biblioteca. Aqui criamos nosso websocket. No html
ele se conecta nessa rota.
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
m.HandleRequest(w, r)
})
E o HandleMessage
faz o Broadcast
para todas as session. Então todos que tiverem conectados no servidor naquele momento vão receber a mensagem.
m.HandleMessage(func(s *melody.Session, msg []byte) {
m.Broadcast(msg)
})