简介
一个用于Go的极简Websocket框架
Melody是基于 github.com/gorilla/websocket框架的,并抽象处理了里面的繁杂部分。
它可以让你搭建一个实时通讯的app,功能包括:
- 接口简单易用类似于net/http或Gin。
- 提供给所有广播以及给选择连接会话广播的简单途径。
- 消息缓冲区使并发写入变得安全。
- 自动处理ping/pong和会话超时。
- 在会话中存储数据。
例子
使用Gin框架完成的聊天室功能
下载依赖包
$ go get -u gopkg.in/olahol/melody.v1
$ go get -u github.com/gin-gonic/gin
main.go
package main
import (
"github.com/gin-gonic/gin"
"gopkg.in/olahol/melody.v1"
"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("/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")
}
index.heml
<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>
展示图:
使用Gin完成文件的实时监控
下载
$ github.com/fsnotify/fsnotify
$ github.com/gin-gonic/gin
$ gopkg.in/olahol/melody.v1
main.go
package main