first version

This commit is contained in:
Ola Holmström
2015-05-13 22:37:17 +02:00
commit fb9197b6ff
12 changed files with 648 additions and 0 deletions
+50
View File
@@ -0,0 +1,50 @@
<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>
+26
View File
@@ -0,0 +1,26 @@
package main
import (
"../../"
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
m := melody.Default()
r.GET("/", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "index.html")
})
r.GET("/ws", func(c *gin.Context) {
m.HandleRequest(c.Writer, c.Request)
})
m.HandleMessage(func(s *melody.Session, msg []byte) {
m.Broadcast(msg)
})
r.Run(":5000")
}
+1
View File
@@ -0,0 +1 @@
Hello World! World Earl
+32
View File
@@ -0,0 +1,32 @@
<html>
<head>
<title>Melody example: file watching</title>
</head>
<style>
#file {
text-align: left;
background: #f1f1f1;
width: 500px;
min-height: 300px;
padding: 20px;
}
</style>
<body>
<center>
<h3>Watching a file</h3>
<pre id="file"></pre>
</center>
<script>
var url = 'ws://' + window.location.host + '/ws';
var c = new WebSocket(url);
c.onmessage = function(msg){
var el = document.getElementById("file");
el.innerText = msg.data;
}
</script>
</body>
</html>
+44
View File
@@ -0,0 +1,44 @@
package main
import (
"../../"
"github.com/gin-gonic/gin"
"github.com/go-fsnotify/fsnotify"
"io/ioutil"
"net/http"
)
func main() {
file := "file.txt"
r := gin.Default()
m := melody.Default()
w, _ := fsnotify.NewWatcher()
r.GET("/", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "index.html")
})
r.GET("/ws", func(c *gin.Context) {
m.HandleRequest(c.Writer, c.Request)
})
m.HandleConnect(func(s *melody.Session) {
content, _ := ioutil.ReadFile(file)
s.Write(content)
})
go func() {
for {
ev := <-w.Events
if ev.Op == fsnotify.Write {
content, _ := ioutil.ReadFile(ev.Name)
m.Broadcast(content)
}
}
}()
w.Add(file)
r.Run(":5000")
}