连续肝了几天, 厚着脸皮再发一次. 目前测试覆盖率已经到达了 95%, 欢迎大家 star, issue 和 PR
向
express
,koa
,gin
致敬!
std http
, lxzan/gws, gorilla/websocketpackage main
import (
"github.com/lxzan/gws"
"github.com/lxzan/uRouter"
gwsAdapter "github.com/lxzan/uRouter/contrib/adapter/gws"
httpAdapter "github.com/lxzan/uRouter/contrib/adapter/http"
"log"
"net/http"
)
func main() {
var router = uRouter.New()
router.Use(uRouter.Recovery(), uRouter.AccessLog())
var upgrader = gws.NewUpgrader(func(c *gws.Upgrader) {
c.EventHandler = NewWebSocketHandler(router, gwsAdapter.NewAdapter(router))
})
router.On("/connect", func(ctx *uRouter.Context) {
r := ctx.Request.Raw
w := ctx.Writer.Raw()
socket, err := upgrader.Accept(w.( http.ResponseWriter), r.(*http.Request))
if err != nil {
log.Println(err.Error())
return
}
socket.Listen()
})
router.Display()
if err := http.ListenAndServe(":3000", httpAdapter.NewAdapter(router)); err != nil {
log.Fatalln(err.Error())
}
}
func NewWebSocketHandler(router *uRouter.Router, adapter *gwsAdapter.Adapter) *WebSocketHandler {
h := &WebSocketHandler{
adapter: adapter,
router: router,
}
group := router.Group("", uRouter.Protocol(uRouter.ProtocolWebSocket))
group.On("/greet", h.Greet)
return h
}
type WebSocketHandler struct {
gws.BuiltinEventEngine
adapter *gwsAdapter.Adapter
router *uRouter.Router
}
func (c *WebSocketHandler) OnMessage(socket *gws.Conn, message *gws.Message) {
if err := c.adapter.ServeWebSocket(socket, message); err != nil {
log.Println(err.Error())
}
}
func (c *WebSocketHandler) Greet(ctx *uRouter.Context) {
var req = uRouter.Any{}
if err := ctx.BindJSON(&req); err != nil {
log.Println(err.Error())
return
}
ctx.Writer.Header().Set(uRouter.ContentType, uRouter.MimeJson)
_ = ctx.WriteJSON(int(gws.OpcodeText), req)
}
let ws = new WebSocket('ws://127.0.0.1:3000/connect')
ws.send('0019{"X-Path":"/greet"}{"hello":"你好, 少侠"}');
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.