multi channel chat demo

This commit is contained in:
Ola Holmström
2015-05-14 19:29:20 +02:00
parent dce8735ee4
commit 4adcb388e6
7 changed files with 154 additions and 28 deletions
+53
View File
@@ -0,0 +1,53 @@
<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 id="name"></h3>
<pre id="chat"></pre>
<input placeholder="say something" id="text" type="text">
</center>
<script>
var url = "ws://" + window.location.host + window.location.pathname + "/ws";
var ws = new WebSocket(url);
var name = "Guest" + Math.floor(Math.random() * 1000);
var channelName = window.location.pathname.split("/")[2];
document.getElementById("name").innerText = "Channel: " + channelName;
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>
Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

+34
View File
@@ -0,0 +1,34 @@
<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>Join a channel</h3>
<input placeholder="channel" id="channel" type="text"><button id="join">Join</button>
</center>
<script>
var chan = document.getElementById("channel");
var join = document.getElementById("join");
join.onclick = function () {
if (chan.value != "") {
window.location = "/channel/" + chan.value;
}
};
</script>
</body>
</html>
+32
View File
@@ -0,0 +1,32 @@
package main
import (
"../../"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
m := melody.New()
r.GET("/", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "index.html")
})
r.GET("/channel/:name", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "chan.html")
})
r.GET("/channel/:name/ws", func(c *gin.Context) {
m.HandleRequest(c.Writer, c.Request)
})
m.HandleMessage(func(s *melody.Session, msg []byte) {
m.BroadcastFilter(msg, func(q *melody.Session) bool {
return q.Request.URL.Path == s.Request.URL.Path
})
})
r.Run(":5000")
}