关于negroni框架的一些疑惑

初学go,最近两天在看negroni的框架代码,现在看了个大概,有些地方不是很明白,有几个疑惑想请教下

  • 自定义的路由表用了middleware这个链表和handler的一个slice。用两个的目的是什么呢,用一个的话我理解也可以吧.我第一眼看到这个脑袋里冒出来的是Mark-Sweep算法。。。
  • 注释说handlers 是 can be,middleware 是 已评估的。这两个是什么意思呢,我看初始化的时候都是直接把注册的*ServeMux搞进去
    // Negroni is a stack of Middleware Handlers that can be invoked as an http.Handler.
    // Negroni middleware is evaluated in the order that they are added to the stack using
    // the Use and UseHandler methods.
    type Negroni struct {
    middleware middleware
    handlers   []Handler
    }
// UseHandler adds a http.Handler onto the middleware stack. Handlers are invoked in the order they are added to a Negroni.
func (n *Negroni) UseHandler(handler http.Handler) {
    n.Use(Wrap(handler))
}
// Use adds a Handler onto the middleware stack. Handlers are invoked in the order they are added to a Negroni.
func (n *Negroni) Use(handler Handler) {
    if handler == nil {
        panic("handler cannot be nil")
    }

    n.handlers = append(n.handlers, handler)
    n.middleware = build(n.handlers)
}
func build(handlers []Handler) middleware {
    var next middleware

    if len(handlers) == 0 {
        return voidMiddleware()
    } else if len(handlers) > 1 {
        next = build(handlers[1:])
    } else {
        next = voidMiddleware()
    }

    return middleware{handlers[0], &next}
}
已邀请:

傅小黑

赞同来自:

middleware{handlers[0],&next} 意思就是这个是链表,是根据 handlers slice 拼成的

// Negroni is a stack of Middleware Handlers that can be invoked as an http.Handler. Negroni 是 Middleware Handlers 的栈,Handlers 可以 作为 http.Handler 被调用

// Negroni middleware is evaluated in the order that they are added to the stack using Negroni middleware 被处理为按照添加到栈的顺序的 middleware 链表来用

只是用一个 handlers 记录 stack,每次添加的时候用 handlers 来生成 middleware 链表

要回复问题请先登录注册