在 websocket app 中使用 gin-like API 处理请求

查看 59|回复 1
作者:Nazz   
连续肝了几天, 厚着脸皮再发一次. 目前测试覆盖率已经到达了 95%, 欢迎大家 star, issue 和 PR

项目地址: https://github.com/lxzan/uRouter


向express, koa, gin 致敬!

特性
  • 通用的 web 路由系统抽象, 核心部分无依赖
  • hashmap 实现的静态路由, 拒绝路径中夹带参数
  • 提供洋葱模型的中间件, 路由组
  • 适配std http, lxzan/gws, gorilla/websocket

    Demo
  • server

    package 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)
    }
  • client

    let ws = new WebSocket('ws://127.0.0.1:3000/connect')
    ws.send('0019{"X-Path":"/greet"}{"hello":"你好, 少侠"}');

    router, urouter, err, ctx

  • learningman   
    “hashmap 实现的静态路由, 拒绝路径中夹带参数”
    好像还挺自豪。。。
    您需要登录后才可以回帖 登录 | 立即注册

    返回顶部