Go

mux 源码分析

2019-05-12  本文已影响1人  小小爱笑

前言

mux 是go实现的轻量的路由,可以基于host,path,query匹配。

使用示例:

r := mux.NewRouter()
r.HandleFunc("/products/{key}", ProductHandler)
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)

源码实现

Router类型结构

type Router struct {
    // Routes to be matched, in order.
    routes []*Route

    // Slice of middlewares to be called after a match is found
    middlewares []middleware

    // configuration shared with `Route`
    routeConf
}

Route类型结构

// Route stores information to match a request and build URLs.
type Route struct {
    // Request handler for the route.
    handler http.Handler

    // config possibly passed in from `Router`
    routeConf
}
type routeConf struct {
    
    // Manager for the variables from host and path.
    regexp routeRegexpGroup

    // List of matchers.
    matchers []matcher

    buildVarsFunc BuildVarsFunc
}

matcher接口

对于不同的匹配类型 抽象出的接口。

// Methods --------------------------------------------------------------------

// methodMatcher matches the request against HTTP methods.
type methodMatcher []string

func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool {
    return matchInArray(m, r.Method)
}

// Methods adds a matcher for HTTP methods.
// It accepts a sequence of one or more methods to be matched, e.g.:
// "GET", "POST", "PUT".
func (r *Route) Methods(methods ...string) *Route {
    for k, v := range methods {
        methods[k] = strings.ToUpper(v)
    }
    return r.addMatcher(methodMatcher(methods))
}

Methods方法添加一个methodMatcher到route的matcher切片中。 methodMatcher的Match方法实现为:取request中的方法进行匹配。

func (r *Route) Path(tpl string) *Route {
    r.err = r.addRegexpMatcher(tpl, regexpTypePath)
    return r
}

Path 方法添加一个支持正则匹配的matcher,类型为regexpTypePath。

routeRegexp 类型结构 是支持参数, 正则 匹配的核心。

type routeRegexp struct {
    // The unmodified template.
    template string
    // The type of match
    regexpType regexpType
    // Options for matching
    options routeRegexpOptions
    // Expanded regexp.
    regexp *regexp.Regexp
    // Reverse template.
    reverse string
    // Variable names.
    varsN []string
    // Variable regexps (validators).
    varsR []*regexp.Regexp
}

addRegexpMatcher方法解析传入的模板字符串,解析出参数和正则表达式存储到 varsN varsR 中。
以 "/articles/{category}/{id:[0-9]+}" 为例,varsN 中保存了 'category', 'id'两个参数,varsR 中保存了 ‘[0-9]+’正则表达式。

Route的Match方法

// Match matches the route against the request.
func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
// Match everything.
    for _, m := range r.matchers {
        if matched := m.Match(req, match); !matched {
            if _, ok := m.(methodMatcher); ok {
                matchErr = ErrMethodMismatch
                continue
            }

            // Ignore ErrNotFound errors. These errors arise from match call
            // to Subrouters.
            //
            // This prevents subsequent matching subrouters from failing to
            // run middleware. If not ignored, the middleware would see a
            // non-nil MatchErr and be skipped, even when there was a
            // matching route.
            if match.MatchErr == ErrNotFound {
                match.MatchErr = nil
            }

            matchErr = nil
            return false
        }
    }
// Set variables.
    r.regexp.setMatch(req, match, r)

}

遍历所有添加的matcher ,所有都匹配则匹配成功。
匹配成功后,提取参数的值。保存到route的routeRegexpGroup类型变量中。

Router实现了http.handler接口

// ServeHTTP dispatches the handler registered in the matched route.
//
// When there is a match, the route variables can be retrieved calling
// mux.Vars(request).
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    var match RouteMatch
    var handler http.Handler
    if r.Match(req, &match) {
        handler = match.Handler
        req = setVars(req, match.Vars)
        req = setCurrentRoute(req, match.Route)
    }

    if handler == nil && match.MatchErr == ErrMethodMismatch {
        handler = methodNotAllowedHandler()
    }

    if handler == nil {
        handler = http.NotFoundHandler()
    }

    handler.ServeHTTP(w, req)
}

调用Match,如果匹配成功。通过setVars将匹配的参数设置到req的context中。
handler处理函数可以通过Vars 从requst中提取参数。 通过context传值 保证了handler接口的一致性。
如果匹配失败,交给http.NotFoundHandler处理。

Router的Match方法

将中间件 添加到 handler处理器 之上

func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
    for _, route := range r.routes {
        if route.Match(req, match) {
            // Build middleware chain if no error was found
            if match.MatchErr == nil {
                for i := len(r.middlewares) - 1; i >= 0; i-- {
                    match.Handler = r.middlewares[i].Middleware(match.Handler)
                }
            }
            return true
        }
    }

    if match.MatchErr == ErrMethodMismatch {
        if r.MethodNotAllowedHandler != nil {
            match.Handler = r.MethodNotAllowedHandler
            return true
        }

        return false
    }

    // Closest match for a router (includes sub-routers)
    if r.NotFoundHandler != nil {
        match.Handler = r.NotFoundHandler
        match.MatchErr = ErrNotFound
        return true
    }

    match.MatchErr = ErrNotFound
    return false
}

参考:
https://github.com/gorilla/mux

上一篇 下一篇

猜你喜欢

热点阅读