Melody 是一个 Go 语言的微型 WebSocket 框架,基于 [github.com/gorilla/websocket](https://github.com/gorilla/websocket) 开发,主要特性:
*
接口简单易用,类似 net/http 或者 [Gin](http://www.oschina.net/p/gin-web-framework)
*
提供给所有广播以及给选择连接会话广播的简单途径
*
消息缓冲对并发写是安全的
*
可自动处理 ping/pong 和会话超时
一个简单的实例:
[![Chat demo](http://static.oschina.net/uploads/img/201505/25075129_vUPd.jpg "Demo")](https://github.com/olahol/melody/tree/master/examples/multichat)
代码:
<pre class="brush:cpp ;toolbar: true; auto-links: false;">package main
import (
"github.com/olahol/melody"
"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")
}</pre>