gorilla/mux 路由指南:基于 Go 标准库的 HTTP 请求多路复用器实战详解

原创2026-10-11 18:42:141,371 阅读
文章标签:CLI开发工具云原生容器编排DevOps

gorilla/mux 路由指南:基于 Go 标准库的 HTTP 请求多路复用器实战详解

本文以当前仓库 vendored 的 gorilla/mux(v1.8.1,见 vendor/modules.txt)官方 README 为核心骨架,结合 mux.go、route.go、regexp.go、middleware.go 等源码实现,系统讲解 gorilla/mux 的路由匹配、路径变量、子路由、URL 反向构建、中间件、CORS 与处理器测试等核心能力,并展示其在 Docker 生态(Docker distribution v2 registry API)中的真实应用方式。读完本文,你将能够用 gorilla/mux 构建结构清晰、支持路径变量与反向 URL、可组合中间件的高质量 Go HTTP 服务。

一、gorilla/mux 是什么

gorilla/mux 是一个请求路由与分发器(request router and dispatcher),用于将传入的 HTTP 请求匹配到对应的处理器(handler)。包名 mux 取自 "HTTP request multiplexer"(HTTP 请求多路复用器)。

与 Go 标准库的 http.ServeMux 类似,mux.Router 会将传入请求与一组已注册的路由进行匹配,并在 URL 或其它条件命中时调用对应路由的处理器。但它比标准库多路复用器提供了更丰富的匹配能力,主要特性包括:

  • 实现 http.Handler 接口:与标准库 http.ServeMux 完全兼容,可直接挂载到 http.ListenAndServe 或作为其它框架的 Handler 使用;
  • 多维匹配条件:可按 URL 主机(host)、路径(path)、路径前缀(path prefix)、协议(scheme)、请求头(header)、查询参数(query value)、HTTP 方法(method)匹配,也支持自定义匹配函数;
  • 路径变量与正则:URL 主机、路径和查询值中可以定义变量,变量可附带可选的正则表达式约束;
  • URL 反向构建(reverse routing):已注册的路由可以反向生成 URL,方便维护对资源的引用,避免在代码中硬编码 URL 字符串;
  • 子路由(subrouter):嵌套路由只在父路由匹配时才被测试,可用于将共享相同条件(如同一 host、同一路径前缀)的一组路由分组,同时优化请求匹配性能。

在 Go 生态中,gorilla/mux 是使用最广泛的第三方路由库之一,其本身由 Gorilla Web Toolkit(一套面向 Go 的 Web 工具包)提供。

二、安装与项目集成

在 README.md 中给出的安装方式是使用 Go 模块机制,前提是已经正确配置了 Go 工具链:

go get -u github.com/gorilla/mux

而在当前 Docker CLI 仓库中,gorilla/mux 是以 vendored 依赖的形式存在的(版本 v1.8.1,声明在 vendor/modules.txt),源码位于 vendor/github.com/gorilla/mux 目录。它并不是被 Docker CLI 主程序直接调用,而是作为 github.com/docker/distribution(Docker Registry v2 协议实现)的依赖被引入——这一点我们在文末"Docker 生态中的真实应用"一节中详细展开。因此,如果你在 Docker CLI 这样的仓库中看到该库,说明它的角色通常是作为 HTTP API 路由层被上层服务(如 registry)使用。

三、快速上手:注册路由与处理器

最基本的用法是调用 mux.NewRouter() 创建路由器,然后通过 HandleFunc 注册 URL 路径与处理器的映射:

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    r.HandleFunc("/products", ProductsHandler)
    r.HandleFunc("/articles", ArticlesHandler)
    http.Handle("/", r)
}

这段代码注册了三条将 URL 路径映射到处理器的路由。它与 http.HandleFunc() 的工作方式等价:当传入请求的 URL 匹配某条路径时,对应的处理器会被调用,并传入 (http.ResponseWriter, *http.Request) 两个参数。

从源码看,HandleFunc 实际是 NewRoute().Path(path).HandlerFunc(f) 的语法糖(见 mux.go),即"新建一条路由 → 添加路径匹配 → 绑定处理器函数"三步合一的便捷入口。Router 实现了 http.Handler 接口,其 ServeHTTP 方法会调用 Match 找到命中路由,再将请求分发到对应处理器(见 mux.go)。

3.1 路径变量

路径中可以定义变量,格式为 {name} 或 {name:pattern}。如果没有定义正则 pattern,匹配的变量将匹配到下一个斜杠之前的任意内容。例如:

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

变量名用于构建一个路由变量(route variables)映射,可以在处理器中通过 mux.Vars() 获取:

func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, "Category: %v\n", vars["category"])
}

3.2 源码原理:变量如何被解析与提取

变量解析的核心实现在 regexp.go 的 newRouteRegexp 函数中。值得注意的几个实现细节:

  • 默认匹配模式因位置而异:路径变量默认 pattern 是 <a href="https://link.gitcode.com/i/e3b63b6d1eede9ed2348d55bbdf25fbc" target="_blank">^/]+(匹配到下一个斜杠为止);查询变量默认是 .*(匹配任意内容);host 变量默认是 [^.]+(匹配到下一个点为止),见 [regexp.go。
  • 非捕获组强制:路由模板中的正则分组必须使用非捕获组 (?:...),如果出现捕获组 (...),newRouteRegexp 会直接 panic(见 regexp.go)。例如应写 /{sort:(?:asc|desc|new)},而不是 /{sort:(asc|desc|new)}。
  • 变量名校验:变量名与 pattern 都不能为空,变量名不能包含冒号;花括号必须成对且平衡,否则返回 mux: unbalanced braces 错误(见 regexp.go 与 regexp.go)。
  • 变量提取时机:路由匹配成功后,routeRegexpGroup.setMatch 会根据正则的命名捕获组把 host、path、query 中的变量提取到 RouteMatch.Vars 映射中(见 regexp.go),随后 ServeHTTP 会通过 requestWithVars 把变量写入请求的 context,供 mux.Vars(r) 读取(见 mux.go)。

四、匹配路由(Matching Routes)

除了路径,路由还可以绑定到多种匹配条件上。下面逐一说明 README 中给出的匹配器。

4.1 Host:限定域名或子域名

通过 Host() 可以限制路由只匹配特定域名或子域名,host 模板同样支持变量:

r := mux.NewRouter()
// Only matches if domain is "www.example.com".
r.Host("www.example.com")
// Matches a dynamic subdomain.
r.Host("{subdomain:[a-z]+}.example.com")

4.2 PathPrefix:匹配路径前缀

r.PathPrefix("/products/")

需要注意:PathPrefix 不做斜杠的"词边界"处理("/foobar/" 也会被前缀 "/foo" 匹配),所以文档建议在需要时使用结尾斜杠(见 route.go 的注释)。另外,PathPrefix 与 StrictSlash 互不影响——前缀路由不会触发尾部斜杠重定向。

4.3 Methods:限定 HTTP 方法

r.Methods("GET", "POST")

源码中 Methods 会先把所有方法名统一转为大写,再生成一个 methodMatcher(见 route.go)。

4.4 Schemes:限定 URL 协议

r.Schemes("https")

Schemes 会把参数统一转为小写,并把第一个参数保存为 URL 反向构建时的默认 scheme(buildScheme),见 route.go。匹配时若请求 URL 未显式携带 scheme,会根据请求的 TLS 终止状态推断:有 TLS 视为 https,否则视为 http(见 route.go)。

4.5 Headers:匹配请求头值

r.Headers("X-Requested-With", "XMLHttpRequest")

Headers 接受一组 key/value 对,要求全部命中才算匹配;如果 value 是空字符串,则表示"只要该 key 存在即可,值任意"(见 route.go)。

4.6 Queries:匹配查询参数值

r.Queries("key", "value")

Queries 同样接受 key/value 对,value 可以包含变量(如 {id:<a href="https://link.gitcode.com/i/f31d1b39ad314baba00a2d4c667b7151" target="_blank">0-9]+}),例如 r.Queries("foo", "bar", "id", "{id:[0-9]+}") 要求 URL 携带 ?foo=bar&id=42。注意参数个数必须是偶数,否则会返回错误(见 [route.go)。

4.7 MatcherFunc:自定义匹配函数

当内置匹配器无法满足需求时,可以用 MatcherFunc 注入任意匹配逻辑,函数签名为 func(*http.Request, *RouteMatch) bool:

r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
    return r.ProtoMajor == 0
})

MatcherFunc 本身也是一个实现了 matcher 接口的类型(见 route.go),所以它可以直接被 addMatcher 挂到路由上。

4.8 组合多个匹配条件

以上匹配器可以自由链式组合在同一条路由上:

r.HandleFunc("/products", ProductsHandler).
  Host("www.example.com").
  Methods("GET").
  Schemes("http")

从 Route.Match 的实现看(route.go),路由保存了一个 matchers 列表,匹配时按注册顺序依次全部通过才算命中;任何一个 matcher 失败则整条路由不匹配。其中方法不匹配会被单独记录为 ErrMethodMismatch,最终可能触发 405 Method Not Allowed 处理。

4.9 匹配顺序:先注册先命中

路由按照注册顺序依次测试,如果两条路由都能匹配,先注册的那条胜出:

r := mux.NewRouter()
r.HandleFunc("/specific", specificHandler)
r.PathPrefix("/").Handler(catchAllHandler)

Router.Match 正是按 r.routes 的切片顺序遍历测试的(见 mux.go)。因此,具体路由要注册在通配/兜底路由之前,这是使用 mux 时最重要的顺序约定之一。

五、子路由(Subrouter):共享条件的路由分组

反复设置相同的匹配条件很繁琐,mux 提供"子路由"机制来分组共享相同条件的路由。

例如,假设有多条 URL 都只在 host 为 www.example.com 时才应被匹配,可以创建一条 host 路由并从中取出子路由:

r := mux.NewRouter()
s := r.Host("www.example.com").Subrouter()

然后在子路由上注册路由:

s.HandleFunc("/products/", ProductsHandler)
s.HandleFunc("/products/{key}", ProductHandler)
s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)

上面三条 URL 只有在域名是 www.example.com 时才会被测试,因为父路由(host 匹配)会先被测试。这不仅方便,还优化了请求匹配:host 不匹配时,子路由中的路由根本不会被遍历。你可以用任意 mux 路由支持的属性匹配器来创建子路由。

从源码看,Subrouter() 会创建一个小型 Router,并把自身(实现了 matcher 接口的 *Router)作为 matcher 挂到父路由上(见 route.go)。Router.Match 遍历父路由时,子路由会作为父路由的一个 matcher 参与匹配。

子路由还可以用来创建域名或路径的"命名空间":在中央位置定义子路由,应用的其他部分再相对于某个子路由注册自己的路径。

子路由还有一个重要特性:当子路由带路径前缀时,内部路由以前缀为基础拼接自己的路径:

r := mux.NewRouter()
s := r.PathPrefix("/products").Subrouter()
// "/products/"
s.HandleFunc("/", ProductsHandler)
// "/products/{key}/"
s.HandleFunc("/{key}/", ProductHandler)
// "/products/{key}/details"
s.HandleFunc("/{key}/details", ProductDetailsHandler)

这种前缀拼接逻辑体现在 addRegexpMatcher 中:新增路径模板会与已有的 path 模板拼接(strings.TrimRight(r.regexp.path.template, "/") + tpl,见 route.go),并且 copyRouteConf 会把父路由的配置(strictSlash、useEncodedPath 等)复制给子路由(见 mux.go)。

六、静态文件服务(Static Files)

PathPrefix() 提供的路径代表一个"通配符":调用 PathPrefix("/static/").Handler(...) 意味着任何匹配 /static/* 的请求都会交给该 handler,因此可以非常方便地用它服务静态文件:

func main() {
    var dir string

    flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
    flag.Parse()
    r := mux.NewRouter()

    // This will serve files under http://localhost:8000/static/<filename>
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))

    srv := &http.Server{
        Handler:      r,
        Addr:         "127.0.0.1:8000",
        // Good practice: enforce timeouts for servers you create!
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

    log.Fatal(srv.ListenAndServe())
}

要点:http.StripPrefix("/static/", ...) 负责剥掉 URL 前缀再交给 http.FileServer,这样浏览器访问 http://localhost:8000/static/<filename> 时,实际映射到本地目录 dir 下的 <filename> 文件。同时 README 强调,为自建的服务器显式设置读写超时是良好的实践。

七、同时服务单页应用(Serving Single Page Applications)

大多数时候,把 SPA(单页应用)和 API 部署在独立的 Web 服务器上是更合理的做法;但有时也希望两者由一个服务承载。可以编写一个简单的 SPA handler(例如配合 React Router 的 BrowserRouter 使用),同时用 mux 强大的路由能力服务 API 端点:

package main

import (
	"encoding/json"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/gorilla/mux"
)

// spaHandler implements the http.Handler interface, so we can use it
// to respond to HTTP requests. The path to the static directory and
// path to the index file within that static directory are used to
// serve the SPA in the given static directory.
type spaHandler struct {
	staticPath string
	indexPath  string
}

// ServeHTTP inspects the URL path to locate a file within the static dir
// on the SPA handler. If a file is found, it will be served. If not, the
// file located at the index path on the SPA handler will be served. This
// is suitable behavior for serving an SPA (single page application).
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Join internally call path.Clean to prevent directory traversal
	path := filepath.Join(h.staticPath, r.URL.Path)

	// check whether a file exists or is a directory at the given path
	fi, err := os.Stat(path)
	if os.IsNotExist(err) || fi.IsDir() {
		// file does not exist or path is a directory, serve index.html
		http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
		return
	}

	if err != nil {
		// if we got an error (that wasn't that the file doesn't exist) stating the
		// file, return a 500 internal server error and stop
		http.Error(w, err.Error(), http.StatusInternalServerError)
        return
	}

	// otherwise, use http.FileServer to serve the static file
	http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
}

func main() {
	router := mux.NewRouter()

	router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
		// an example API handler
		json.NewEncoder(w).Encode(map[string]bool{"ok": true})
	})

	spa := spaHandler{staticPath: "build", indexPath: "index.html"}
	router.PathPrefix("/").Handler(spa)

	srv := &http.Server{
		Handler: router,
		Addr:    "127.0.0.1:8000",
		// Good practice: enforce timeouts for servers you create!
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}

	log.Fatal(srv.ListenAndServe())
}

关键思路:spaHandler 实现 http.Handler 接口;它先检查静态目录中是否存在与 URL 路径对应的真实文件,存在则交给 http.FileServer 服务,不存在(或路径指向目录)则回退返回 index.html——这正是 SPA 前端路由(如 React Router 的 BrowserRouter)所依赖的行为。同时 /api/health 等 API 路由由 mux 正常匹配,二者共存于同一个 Router。代码注释还专门提醒:filepath.Join 内部会调用 path.Clean,因此可以防范目录穿越攻击。

八、命名路由与 URL 反向构建(Registered URLs)

8.1 基本反向构建

路由可以命名,所有定义了名称的路由都可以被反向构建("reversed")出 URL。通过 Name() 给路由命名:

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

构建 URL 时,先通过 r.Get("article") 取回命名路由,再调用 URL() 方法,传入一组路由变量的 key/value 对:

url, err := r.Get("article").URL("category", "technology", "id", "42")

结果是一个 url.URL,其路径为:

"/articles/technology/42"

8.2 host 与 query 变量同样支持反向构建

r := mux.NewRouter()
r.Host("{subdomain}.example.com").
  Path("/articles/{category}/{id:[0-9]+}").
  Queries("filter", "{filter}").
  HandlerFunc(ArticleHandler).
  Name("article")

// url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla"
url, err := r.Get("article").URL("subdomain", "news",
                                 "category", "technology",
                                 "id", "42",
                                 "filter", "gorilla")

路由中定义的所有变量都是必需的,且传入值必须符合对应的正则模式。这些约束保证了生成的 URL 一定能被注册的路由重新匹配——唯一的例外是显式标记为 build-only(只用于构建、永不匹配)的路由。

8.3 请求头正则匹配

正则支持同样适用于路由内的请求头匹配:

r.HeadersRegexp("Content-Type", "application/(text|json)")

上面这条路由对 Content-Type 为 application/json 以及 application/text 的请求都能命中。

8.4 只构建 host 或 path

还可以用 URLHost() 或 URLPath() 只构建 URL 的主机或路径部分:

// "http://news.example.com/"
host, err := r.Get("article").URLHost("subdomain", "news")

// "/articles/technology/42"
path, err := r.Get("article").URLPath("category", "technology", "id", "42")

如果使用子路由,分别定义的 host 和 path 同样可以组合构建:

r := mux.NewRouter()
s := r.Host("{subdomain}.example.com").Subrouter()
s.Path("/articles/{category}/{id:[0-9]+}").
  HandlerFunc(ArticleHandler).
  Name("article")

// "http://news.example.com/articles/technology/42"
url, err := r.Get("article").URL("subdomain", "news",
                                 "category", "technology",
                                 "id", "42")

8.5 查询某条路由的全部必需变量

调用 URL() 前,可以用 GetVarNames() 找出该路由需要的全部变量名:

r := mux.NewRouter()
r.Host("{domain}").
    Path("/{group}/{item_id}").
    Queries("some_data1", "{some_data1}").
    Queries("some_data2", "{some_data2}").
    Name("article")

// Will print [domain group item_id some_data1 some_data2] <nil>
fmt.Println(r.Get("article").GetVarNames())

GetVarNames 依次收集 host、path、queries 三部分正则模板中的变量名(见 route.go),返回的切片顺序即为传入 URL() 时的键值对顺序。

8.6 源码原理:URL 如何被构建与校验

反向构建的底层实现在 regexp.go 的 routeRegexp.url 中:模板解析时,mux 会同时生成一份"反向模板"(reverse template,形如 "/articles/%s/%s",见 regexp.go),构建 URL 时把各变量值 fmt.Sprintf 填充进去,其中 query 变量的值会先经过 url.QueryEscape 转义(见 regexp.go)。

填充完成后,结果还会用完整正则再校验一次;如果整体不匹配,则逐个变量用各自的校验正则(^pattern$)检查,从而给出精确的错误信息("variable %q doesn't match, expected %q")。这解释了 README 中"值必须符合模式,否则保证生成 URL 能重新匹配"这一承诺的来源。此外,BuildVarsFunc 允许在构建 URL 前统一改写变量(多个函数会链式组合,见 route.go)。

九、路由遍历(Walking Routes)

mux.Router 的 Walk 函数可以访问注册在路由器上的所有路由,典型用途是打印全部注册路由、生成 API 文档或做路由层面的埋点。

package main

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
)

func handler(w http.ResponseWriter, r *http.Request) {
	return
}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", handler)
	r.HandleFunc("/products", handler).Methods("POST")
	r.HandleFunc("/articles", handler).Methods("GET")
	r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT")
	r.HandleFunc("/authors", handler).Queries("surname", "{surname}")
	err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
		pathTemplate, err := route.GetPathTemplate()
		if err == nil {
			fmt.Println("ROUTE:", pathTemplate)
		}
		pathRegexp, err := route.GetPathRegexp()
		if err == nil {
			fmt.Println("Path regexp:", pathRegexp)
		}
		queriesTemplates, err := route.GetQueriesTemplates()
		if err == nil {
			fmt.Println("Queries templates:", strings.Join(queriesTemplates, ","))
		}
		queriesRegexps, err := route.GetQueriesRegexp()
		if err == nil {
			fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ","))
		}
		methods, err := route.GetMethods()
		if err == nil {
			fmt.Println("Methods:", strings.Join(methods, ","))
		}
		fmt.Println()
		return nil
	})

	if err != nil {
		fmt.Println(err)
	}

	http.Handle("/", r)
}

Walk 的回调会收到三条信息:当前路由、当前路由器、以及通向该路由的祖先路由链(ancestors)。从实现看,Walk 按路由注册顺序以深度优先方式遍历整棵路由树,包括嵌套的子路由;回调返回 SkipRouter 可以跳过对某个子路由的继续深入(见 mux.go)。示例中用到的 GetPathTemplate、GetPathRegexp、GetQueriesTemplates、GetQueriesRegexp、GetMethods 等查询方法都定义在 route.go 中,它们的文档注释明确提到"对构建简单的 REST API 文档和第三方服务埋点很有用"。

十、优雅关闭(Graceful Shutdown)

Go 1.8 起,*http.Server 支持优雅关闭。下面演示如何在 mux 服务上配合信号处理实现优雅退出:

package main

import (
    "context"
    "flag"
    "log"
    "net/http"
    "os"
    "os/signal"
    "time"

    "github.com/gorilla/mux"
)

func main() {
    var wait time.Duration
    flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
    flag.Parse()

    r := mux.NewRouter()
    // Add your routes as needed

    srv := &http.Server{
        Addr:         "0.0.0.0:8080",
        // Good practice to set timeouts to avoid Slowloris attacks.
        WriteTimeout: time.Second * 15,
        ReadTimeout:  time.Second * 15,
        IdleTimeout:  time.Second * 60,
        Handler: r, // Pass our instance of gorilla/mux in.
    }

    // Run our server in a goroutine so that it doesn't block.
    go func() {
        if err := srv.ListenAndServe(); err != nil {
            log.Println(err)
        }
    }()

    c := make(chan os.Signal, 1)
    // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
    // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
    signal.Notify(c, os.Interrupt)

    // Block until we receive our signal.
    <-c

    // Create a deadline to wait for.
    ctx, cancel := context.WithTimeout(context.Background(), wait)
    defer cancel()
    // Doesn't block if no connections, but will otherwise wait
    // until the timeout deadline.
    srv.Shutdown(ctx)
    // Optionally, you could run srv.Shutdown in a goroutine and block on
    // <-ctx.Done() if your application should wait for other services
    // to finalize based on context cancellation.
    log.Println("shutting down")
    os.Exit(0)
}

几个要点:服务器在独立的 goroutine 中运行,主 goroutine 阻塞等待 os.Interrupt(Ctrl+C);收到信号后用带超时上限的 context 调用 srv.Shutdown,给存量连接一个完成的宽限期;IdleTimeout 用于释放闲置连接。注意 srv.Shutdown(ctx) 在无连接时会立即返回,否则会一直等待直到 deadline 到期。

十一、中间件(Middleware)

mux 支持为 Router 添加中间件,中间件在匹配成功后按添加顺序执行,对子路由同样生效。中间件是(通常很小的)一段代码:接收一个请求、做点处理、再把它交给下一个中间件或最终处理器。常见用途包括请求日志、请求头改写、ResponseWriter 劫持等。

mux 中间件使用 Go 事实标准类型:

type MiddlewareFunc func(http.Handler) http.Handler

通常,返回的 handler 是一个闭包:它对传入的 http.ResponseWriter 和 http.Request 做处理,然后调用 MiddlewareFunc 参数传入的 handler。闭包能访问其创建上下文中的变量,同时保持接收方强制的方法签名。

一个记录请求 URI 的基础中间件:

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Do stuff here
        log.Println(r.RequestURI)
        // Call the next handler, which can be another middleware in the chain, or the final handler.
        next.ServeHTTP(w, r)
    })
}

通过 Router.Use() 把中间件挂到路由器上:

r := mux.NewRouter()
r.HandleFunc("/", handler)
r.Use(loggingMiddleware)

一个更复杂的认证中间件——把会话 token 映射到用户:

// Define our struct
type authenticationMiddleware struct {
	tokenUsers map[string]string
}

// Initialize it somewhere
func (amw *authenticationMiddleware) Populate() {
	amw.tokenUsers["00000000"] = "user0"
	amw.tokenUsers["aaaaaaaa"] = "userA"
	amw.tokenUsers["05f717e5"] = "randomUser"
	amw.tokenUsers["deadbeef"] = "user0"
}

// Middleware function, which will be called for each request
func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := r.Header.Get("X-Session-Token")

        if user, found := amw.tokenUsers[token]; found {
        	// We found the token in our map
        	log.Printf("Authenticated user %s\n", user)
        	// Pass down the request to the next middleware (or final handler)
        	next.ServeHTTP(w, r)
        } else {
        	// Write an error and stop the handler chain
        	http.Error(w, "Forbidden", http.StatusForbidden)
        }
    })
}
r := mux.NewRouter()
r.HandleFunc("/", handler)

amw := authenticationMiddleware{tokenUsers: make(map[string]string)}
amw.Populate()

r.Use(amw.Middleware)

需要注意:如果中间件不调用 next.ServeHTTP(),处理器链就会在此中断——这可以被有意用来终止请求。中间件在要终止请求时应当写 ResponseWriter,在不终止请求时则不应写。

源码侧,Use 会把中间件追加到 Router.middlewares 切片(见 middleware.go);Router.Match 命中路由后,会从链尾到链首逐个包装 handler,最终形成"后注册的中间件更靠近处理器"的洋葱式调用链(见 mux.go)。

十二、处理 CORS 请求

CORSMethodMiddleware 旨在简化 Access-Control-Allow-Methods 响应头的设置。使用它的几个约定:

  • 仍需要用自己的 CORS handler 设置其它 CORS 头,例如 Access-Control-Allow-Origin;
  • 该中间件会把路由上全部方法匹配器(例如 r.Methods(http.MethodGet, http.MethodPut, http.MethodOptions) 对应 Access-Control-Allow-Methods: GET,PUT,OPTIONS)写入响应头;
  • 如果路由没有显式声明方法:必须存在 OPTIONS 方法匹配器,中间件才会设置响应头。

下面是 CORSMethodMiddleware 配合自定义 OPTIONS handler 设置全部必需 CORS 头的示例:

package main

import (
	"net/http"
	"github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    // IMPORTANT: you must specify an OPTIONS method matcher for the middleware to set CORS headers
    r.HandleFunc("/foo", fooHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodOptions)
    r.Use(mux.CORSMethodMiddleware(r))

    http.ListenAndServe(":8080", r)
}

func fooHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    if r.Method == http.MethodOptions {
        return
    }

    w.Write([]byte("foo"))
}

用 curl 发一个请求:

curl localhost:8080/foo -v

响应大致如下:

*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /foo HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.59.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS
< Access-Control-Allow-Origin: *
< Date: Fri, 28 Jun 2019 20:13:30 GMT
< Content-Length: 3
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
foo

可以看到,响应中同时出现了 Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS 和自定义 handler 设置的 Access-Control-Allow-Origin: *。

从实现看,CORSMethodMiddleware 通过 getAllMethodsForRoute 遍历路由,找出与当前请求匹配(或仅方法不匹配 ErrMethodMismatch)的路由,收集其全部方法(见 middleware.go),随后仅当收集到的方法集合中包含 OPTIONS 时才设置响应头——这正是"必须声明 OPTIONS 方法"这一约束的源码出处。

十三、测试处理器(Testing Handlers)

在 Go Web 应用中测试 handler 很直接,mux 不会让这件事变得更复杂。假设有两个文件:endpoints.go 和 endpoints_test.go。

先看简单的 HTTP handler:

// endpoints.go
package main

func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
    // A very simple health check.
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)

    // In the future we could report back on the status of our DB, or our cache
    // (e.g. Redis) by performing a simple PING, and include them in the response.
    io.WriteString(w, `{"alive": true}`)
}

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/health", HealthCheckHandler)

    log.Fatal(http.ListenAndServe("localhost:8080", r))
}

对应的测试代码:

// endpoints_test.go
package main

import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestHealthCheckHandler(t *testing.T) {
    // Create a request to pass to our handler. We don't have any query parameters for now, so we'll
    // pass 'nil' as the third parameter.
    req, err := http.NewRequest("GET", "/health", nil)
    if err != nil {
        t.Fatal(err)
    }

    // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(HealthCheckHandler)

    // Our handlers satisfy http.Handler, so we can call their ServeHTTP method
    // directly and pass in our Request and ResponseRecorder.
    handler.ServeHTTP(rr, req)

    // Check the status code is what we expect.
    if status := rr.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }

    // Check the response body is what we expect.
    expected := `{"alive": true}`
    if rr.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %v want %v",
            rr.Body.String(), expected)
    }
}

测试思路:用 httptest.NewRecorder()(实现了 http.ResponseWriter)记录响应,直接调用 handler 的 ServeHTTP 方法传入请求与记录器,再断言状态码与响应体。

当路由带有变量时,可以把变量放进请求中测试。可以采用表驱动测试(table-driven tests)覆盖多种可能的路径变量组合。例如:

// endpoints.go
func main() {
    r := mux.NewRouter()
    // A route with a route variable:
    r.HandleFunc("/metrics/{type}", MetricsHandler)

    log.Fatal(http.ListenAndServe("localhost:8080", r))
}

对应的表驱动测试:

// endpoints_test.go
func TestMetricsHandler(t *testing.T) {
    tt := []struct{
        routeVariable string
        shouldPass bool
    }{
        {"goroutines", true},
        {"heap", true},
        {"counters", true},
        {"queries", true},
        {"adhadaeqm3k", false},
    }

    for _, tc := range tt {
        path := fmt.Sprintf("/metrics/%s", tc.routeVariable)
        req, err := http.NewRequest("GET", path, nil)
        if err != nil {
            t.Fatal(err)
        }

        rr := httptest.NewRecorder()

	// To add the vars to the context,
	// we need to create a router through which we can pass the request.
	router := mux.NewRouter()
        router.HandleFunc("/metrics/{type}", MetricsHandler)
        router.ServeHTTP(rr, req)

        // In this case, our MetricsHandler returns a non-200 response
        // for a route variable it doesn't know about.
        if rr.Code == http.StatusOK && !tc.shouldPass {
            t.Errorf("handler should have failed on routeVariable %s: got %v want %v",
                tc.routeVariable, rr.Code, http.StatusOK)
        }
    }
}

这里的技巧是:要让 mux.Vars(r) 在处理器内生效,必须把请求真正经过一个 mux.Router 分发(因为变量存放在请求的 context 中,由 Router.ServeHTTP 负责注入),所以测试里先 mux.NewRouter() 注册同样的路由,再 router.ServeHTTP(rr, req) 驱动请求。

十四、完整可运行示例(Full Example)

下面是一个完整、可运行的小型 mux 服务:

package main

import (
    "net/http"
    "log"
    "github.com/gorilla/mux"
)

func YourHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Gorilla!\n"))
}

func main() {
    r := mux.NewRouter()
    // Routes consist of a path and a handler function.
    r.HandleFunc("/", YourHandler)

    // Bind to a port and pass our router in
    log.Fatal(http.ListenAndServe(":8000", r))
}

运行后访问 http://localhost:8000/,即可看到 Gorilla! 响应。这是将 mux.Router 直接作为 http.Server 根 handler 的最简形态——因为 Router 实现了 http.Handler 接口(mux.go),它可以无缝替换标准库的 http.ServeMux。

十五、源码层面的重要配置项补充

除了 README 正文,源码中还定义了三个与路由行为密切相关的 Router 配置方法,理解它们有助于写出行为可预期的路由表:

  • StrictSlash(bool):控制尾部斜杠行为。为 true 时,若路由路径是 "/path/",访问 "/path" 会 301 重定向到前者,反之亦然,应用始终看到路由中声明的路径形式;为 false(默认)时二者互不匹配。注意对 POST/PUT 等非幂等方法,301 重定向后大多数客户端会用 GET 重发,需要自行处理(见 mux.go)。该重定向逻辑实现在 regexp.go:匹配成功后比较 path 与模板的结尾斜杠,不一致则替换 handler 为 http.RedirectHandler(301)。
  • SkipClean(bool):控制路径清理行为。默认会对路径做规范化清理,例如 /fetch/http://xkcd.com/534/ 会被清理成 /fetch/http/xkcd.com/534;设为 true 后保留原始双斜杠等形态,适用于像 /fetch/<完整URL> 这类路由(见 mux.go)。ServeHTTP 中还会对清理后的路径与原始路径不一致的情况直接 301 重定向(见 mux.go)。
  • UseEncodedPath():让路由匹配原始编码路径而非解码后的路径。例如 /path/foo%2Fbar/to 默认按 /path/foo/bar/to 参与匹配,启用后则按编码形态 /path/foo%2Fbar/to 匹配,从而可以命中 /path/{var}/to(见 mux.go)。

另外,Router 还支持两个自定义兜底处理器:NotFoundHandler 与 MethodNotAllowedHandler,分别用于渲染自定义的 404 与 405 响应(见 mux.go)。当路由方法不匹配时 Match 会返回 ErrMethodMismatch,优先触发 405 处理器;没有任何路由命中时返回 ErrNotFound,触发 404 处理器(见 mux.go)。

十六、Docker 生态中的真实应用:Registry v2 API 路由

作为佐证,gorilla/mux 在当前仓库的 vendored 依赖 github.com/docker/distribution(Docker Registry v2 协议)中被实际使用。在 vendor/github.com/docker/distribution/registry/api/v2/routes.go 中:

// The following are definitions of the name under which all V2 routes are
// registered. These symbols can be used to look up a route based on the name.
const (
	RouteNameBase            = "base"
	RouteNameManifest        = "manifest"
	RouteNameTags            = "tags"
	RouteNameBlob            = "blob"
	RouteNameBlobUpload      = "blob-upload"
	RouteNameBlobUploadChunk = "blob-upload-chunk"
	RouteNameCatalog         = "catalog"
)

// Router builds a gorilla router with named routes for the various API
// methods. This can be used directly by both server implementations and
// clients.
func Router() *mux.Router {
	return RouterWithPrefix("")
}

// RouterWithPrefix builds a gorilla router with a configured prefix
// on all routes.
func RouterWithPrefix(prefix string) *mux.Router {
	rootRouter := mux.NewRouter()
	router := rootRouter
	if prefix != "" {
		router = router.PathPrefix(prefix).Subrouter()
	}

	router.StrictSlash(true)

	for _, descriptor := range routeDescriptors {
		router.Path(descriptor.Path).Name(descriptor.Name)
	}
	return rootRouter
}

这段代码把本文讲到的多项能力用在了同一处:

  • 子路由 + 路径前缀命名空间:当需要挂载前缀(如 /v2/)时,通过 router.PathPrefix(prefix).Subrouter() 创建带前缀的子路由,所有 API 路由都相对该前缀注册;
  • 命名路由:为 manifest、blob、tags、catalog 等资源定义了常量名(RouteNameManifest 等),后续通过 Route.Get(name) 即可反向构建 URL;
  • StrictSlash:统一开启尾部斜杠归一化。

这些命名路由随后在 urls.go 中被大量用于反向构建 URL,例如:

manifestURL, err := route.URL("name", ref.Name(), "reference", tagOrDigest)
tagsURL, err := route.URL("name", name.Name())
uploadURL, err := route.URL("name", name.Name(), "uuid", uuid)

即通过 route.URL(pairs...) 传入资源名、摘要、上传 UUID 等变量值,生成指向具体资源的完整 URL。这正是 README 中"反向路由有助于维护对资源的引用"这一特性的生产级实践——服务器端实现与客户端都可以共享同一套路由定义(Router() 的注释明确写着"This can be used directly by both server implementations and clients")。路由描述符则定义在 descriptors.go 中,每条描述符带 Name 字段与 RouteNameManifest 等常量对应。

十七、许可证

gorilla/mux 采用 BSD 许可证发布,详细信息见仓库内的 vendor/github.com/gorilla/mux/LICENSE 文件。

登录后查看全文
cli