连续肝了几天, 目前测试覆盖率已经到达了95%, 欢迎大家star, issue和PR
> 项目地址: https://github.com/lxzan/uRouter
> 向`express`, `koa`, `gin` 致敬!
### 特性
- 通用的web路由系统抽象, 核心部分无依赖
- hashmap实现的静态路由, 拒绝路径中夹带参数
- 提供洋葱模型的中间件, 路由组
- 适配`std http`, [lxzan/gws](https://github.com/lxzan/gws), [gorilla/websocket](https://github.com/gorilla/websocket)
### Demo
- server
```go
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
```js
let ws = new WebSocket('ws://127.0.0.1:3000/connect')
ws.send('0019{"X-Path":"/greet"}{"hello":"你好, 少侠"}');
```
有疑问加站长微信联系(非本文作者)