MelodyGo 的 WebSocket 框架
Melody 是一个 Go 语言的微型 WebSocket 框架,基于 github.com/gorilla/websocket 开发,主要特性:
-  
接口简单易用,类似 net/http 或者 Gin
 -  
提供给所有广播以及给选择连接会话广播的简单途径
 -  
消息缓冲对并发写是安全的
 -  
可自动处理 ping/pong 和会话超时
 
一个简单的实例:
代码:
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")
}评论
