项目地址: https://github.com/lxzan/uRouter
向express, koa, gin 致敬!
特性
Demo
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)
}
let ws = new WebSocket('ws://127.0.0.1:3000/connect')
ws.send('0019{"X-Path":"/greet"}{"hello":"你好, 少侠"}');