关于golang:七天实现web框架分组路由

47次阅读

共计 2092 个字符,预计需要花费 6 分钟才能阅读完成。

在我的项目中咱们很多时候会对一组的路由进行解决,咱们应该如何实现这个性能呢。目前来说,咱们进行的都是单个路由的解决。

分组的实现

明天的内容不是很多,咱们对 router 文件进行改在。
在分组的时候,给每个组要用本人的中间件,也就是共有的中间件,所以咱们首先实现一个构造体

type RouterGroup struct {
    prefix      string
    middlewares []HandlerFunc // support middleware
    parent      *RouterGroup  // support nesting
    engine      *Engine       // all groups share a Engine instance
}

而后 engine 要实现所以的性能,所以咱们要进行一个革新:

func New() *Engine {engine := &Engine{router: newRouter()}
    engine.RouterGroup = &RouterGroup{engine: engine}
    engine.groups = []*RouterGroup{engine.RouterGroup}
    return engine
}

而后上面是咱们是咱们总体的代码:

package gee

import (
    "log"
    "net/http"
)

type RouterGroup struct {
    prefix      string
    middlewares []HandlerFunc // support middleware
    parent      *RouterGroup  // support nesting
    engine      *Engine       // all groups share a Engine instance
}

// HandlerFunc defines the request handler used by gee
type HandlerFunc func(*Context)

// Engine implement the interface of ServeHTTP
type Engine struct {
    *RouterGroup
    router *router
    groups []*RouterGroup // store all groups}

// New is the constructor of gee.Engine
func New() *Engine {engine := &Engine{router: newRouter()}
    engine.RouterGroup = &RouterGroup{engine: engine}
    engine.groups = []*RouterGroup{engine.RouterGroup}
    return engine
}

// Group is defined to create a new RouterGroup
// remember all groups share the same Engine instance
func (group *RouterGroup) Group(prefix string) *RouterGroup {
    engine := group.engine
    newGroup := &RouterGroup{
        prefix: group.prefix + prefix,
        parent: group,
        engine: engine,
    }
    engine.groups = append(engine.groups, newGroup)
    return newGroup
}

func (group *RouterGroup) addRoute(method string, comp string, handler HandlerFunc) {
    pattern := group.prefix + comp
    log.Printf("Route %4s - %s", method, pattern)
    group.engine.router.addRoute(method, pattern, handler)
}

// GET defines the method to add GET request
func (group *RouterGroup) GET(pattern string, handler HandlerFunc) {group.addRoute("GET", pattern, handler)
}

// POST defines the method to add POST request
func (group *RouterGroup) POST(pattern string, handler HandlerFunc) {group.addRoute("POST", pattern, handler)
}

// Run defines the method to start a http server
func (engine *Engine) Run(addr string) (err error) {return http.ListenAndServe(addr, engine)
}

// 这里就是最初的处理函数,这里开始建设的上下文。func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {c := newContext(w, req)
    engine.router.handle(c)
}

正文完
 0