Grafana Mimir 的 HTTP 路由基石:gorilla/mux 路由库深度解析与实战

原创2026-10-14 15:16:151,449 阅读
文章标签:时序数据库后端数据存储可观测性云原生

Grafana Mimir 的 HTTP 路由基石:gorilla/mux 路由库深度解析与实战

本文以仓库中 vendor 的 gorilla/mux README 为主体,系统讲解这个 "HTTP 请求多路复用器" 的路由注册、匹配器、子路由、URL 反向构造、中间件与测试方法,并结合 Grafana Mimir 源码中真实的路由注册代码(pkg/api、pkg/mimir、pkg/compactor)说明该库在生产级多租户 HTTP API 中的落地方式。读完后,你将能够完整掌握 gorilla/mux 的 API 体系,并理解 Mimir 如何在它之上组织鉴权、gzip、限流等请求处理链。

gorilla/mux 是什么

gorilla/mux 是一个请求路由与分发器:mux.Router 将入站请求与一组已注册路由进行匹配,并调用匹配路由对应的处理器。mux 即 "HTTP request multiplexer",其设计与标准库 http.ServeMux 一脉相承,但能力更强。README 列出的核心特性包括:

  • 实现 http.Handler 接口,与标准库 http.ServeMux 完全兼容;
  • 可以基于 URL host、路径、路径前缀、scheme、header、query 值、HTTP 方法或自定义匹配函数来匹配请求;
  • URL 的 host、path、query 值都可以定义变量,且变量可附加可选的正则表达式约束;
  • 已注册的 URL 可以被"构建"(即反向构造,reverse),方便维护对资源 URL 的引用;
  • 路由可以作为子路由(subrouter)使用:嵌套路由只有在其父路由匹配时才会被测试,这既能定义共享 host、路径前缀等公共条件的一组路由,也顺带优化了请求匹配性能。

在当前仓库中,Mimir 通过 go.mod 固定依赖版本为 github.com/gorilla/mux v1.8.1(见 go.mod 第 19 行),源码整体 vendored 在 vendor/github.com/gorilla/mux/ 目录下,包含 mux.go(Router 与 Vars)、route.go(Route 与匹配器)、regexp.go(路由变量正则)、middleware.go(MiddlewareFunc 与 CORSMethodMiddleware)等文件,BSD 许可(见 LICENSE)。

安装

在正确配置好的 Go 工具链下:

go get -u github.com/gorilla/mux

对于已经 vendor 依赖的仓库(如本仓库),该库源码可以直接在 vendor/github.com/gorilla/mux/ 下阅读。

基础用法:注册路由、路径变量与 mux.Vars()

最基础的用法是注册若干 URL 路径与处理器的映射:

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

这里注册了三条路由。这与 http.HandleFunc() 的工作方式等价:当入站请求的 URL 匹配某条路径时,对应的处理器会以 (http.ResponseWriter, *http.Request) 作为参数被调用。

路径可以带变量,格式为 {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)

变量名用于构建一个路由变量映射,可通过 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"])
}

在 vendored 源码中,Vars() 定义于 mux.go 第 430 行,它从请求 context 中读取匹配成功时写入的路由变量表。

Mimir 中的真实用例:Mimir 的 block 上传 API 就使用了带变量的路径。路由在 pkg/api/api.go 第 464-467 行 注册:

a.RegisterRoute("/api/v1/upload/block/{block}/start", http.HandlerFunc(c.StartBlockUpload), true, false, http.MethodPost)
a.RegisterRoute("/api/v1/upload/block/{block}/files", a.DisableServerHTTPTimeouts(http.HandlerFunc(c.UploadBlockFile)), true, false, http.MethodPost)
a.RegisterRoute("/api/v1/upload/block/{block}/finish", http.HandlerFunc(c.FinishBlockUpload), true, false, http.MethodPost)
a.RegisterRoute("/api/v1/upload/block/{block}/check", http.HandlerFunc(c.GetBlockUploadStateHandler), true, false, http.MethodGet)

而处理器一侧在 pkg/compactor/block_upload.go 第 201-219 行 中,正是通过 mux.Vars() 取出 {block} 变量并解析为 ULID:

// parseBlockUploadParameters parses common parameters from the request: block ID, tenant and checks if tenant has uploads enabled.
func (c *MultitenantCompactor) parseBlockUploadParameters(r *http.Request) (ulid.ULID, string, error) {
    blockID, err := ulid.Parse(mux.Vars(r)["block"])
    if err != nil {
        return ulid.ULID{}, "", errors.New("invalid block ID")
    }
    // ...
}

类似的 mux.Vars() 用法还出现在 pkg/ruler/api.go、pkg/ingester/tenants_http.go、pkg/storegateway/gateway_blocks_http.go、pkg/usagetracker/debug_http.go 等模块中,是 Mimir 各 HTTP API 读取路径变量的统一方式。

路由匹配:多维匹配器、匹配顺序与子路由

路由还可以限定域名或子域名,只需定义一个要匹配的 host pattern,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")

还可以叠加多种匹配器:匹配路径前缀——

r.PathPrefix("/products/")

匹配 HTTP 方法——

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

匹配 URL scheme——

r.Schemes("https")

匹配 header 值——

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

匹配 query 值——

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

使用自定义匹配函数:

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

最后,可以在单条路由上组合多个匹配器:

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

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

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

子路由(subrouting):反复书写相同的匹配条件很枯燥,因此 mux 提供了把共享同一组条件的路由归为一组的方式——子路由。例如一组 URL 只应在 host 为 www.example.com 时才匹配,可以这样创建子路由:

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)

上面三条路径只有当域名为 www.example.com 时才会被测试,因为子路由会先被测试。这不仅是方便,还优化了请求匹配。你可以用任意路由匹配器组合来创建子路由。子路由可以用来创建域名或路径"命名空间":在中心位置定义好子路由,然后应用的各个部分相对于给定子路由注册自己的路径。

关于子路由还有另一要点:当子路由带有路径前缀时,内部路由会以前缀作为路径基础:

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)

Mimir 中的对应实践:Mimir 的 HTTP 服务由 dskit server 承载。pkg/api/api.go 第 276-280 行 附近的注释明确写道:"The dskit server registers all routes on a subrouter rooted at -server.path-prefix",即当配置了 server.path-prefix 时,dskit 会在根路由之下建一个按路径前缀划分的子路由。因此 Mimir 在注册静态资源前缀时需要先剥掉该前缀:

a.RegisterRoutesWithPrefix("/static/", http.StripPrefix(a.cfg.ServerPrefix, http.FileServer(http.FS(staticFiles))), false, true, 0, "GET")

这正是 README "子路由路径前缀" 一节所述"内部路由以前缀为基址"行为在真实项目中的体现。

静态文件服务

注意传给 PathPrefix() 的路径是一个"通配符":PathPrefix("/static/").Handler(...) 意味着任何匹配 /static/* 的请求都会交给该 handler。这让用 mux 服务静态文件变得很简单:

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())
}

Mimir 同样采用"前缀 + http.StripPrefix + http.FileServer"这一组合:RegisterRoutesWithPrefix("/static/", ...)(pkg/api/api.go 第 280 行)将内嵌的静态资源(页面 CSS/JS 等,存放于 pkg/api/static/)暴露在 /static/<filename> 下。

服务单页应用(SPA)

大多数时候把 SPA 和 API 分开部署更合理,但有时希望从同一处同时服务两者。可以写一个简单的 handler 来服务 SPA(例如配合 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())
}

这个示例同时演示了一个重要技巧:注册顺序——/api/health 先注册、PathPrefix("/") 的兜底 handler 后注册,保证 API 路由优先命中,与上文"先注册者获胜"的规则一致。

已注册 URL 的反向构造(Named Routes)

路由可以命名,所有定义了名字的路由都可以反向构建 URL。通过 Name() 定义名字:

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

构建 URL 时,取出路由并调用 URL() 方法,传入一组键值对作为路由变量:

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

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

"/articles/technology/42"

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")

路由中定义的所有变量都是必需的,且取值必须满足对应 pattern。这些约束保证了生成的 URL 一定能匹配已注册的路由——唯一例外是显式定义的"仅用于构建"(build-only)路由,它们从不参与匹配。

header 的正则匹配也支持,例如:

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

该路由同时匹配 Content-Type 为 application/json 和 application/text 的请求。

如果只想构建 URL 的 host 或 path 部分,使用 URLHost() 或 URLPath() 方法:

// "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")

调用 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())

遍历路由(Walking Routes)

mux.Router 的 Walk 函数可用于访问 router 上注册的所有路由。下面的例子打印全部已注册路由及其模板、正则、方法等元信息:

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 []*mux.Route 参数,因此它还能还原出子路由层级关系,适合用于生成 API 文档或启动时的路由清单日志。

优雅停机(Graceful Shutdown)

Go 1.8 引入了对 *http.Server 进行优雅停机的能力。与 mux 配合的完整写法如下(注意服务器需放入 goroutine 运行以便接收信号,并通过 context.WithTimeout 控制等待窗口):

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)
}

Mimir 本身的多模块优雅停机由 dskit 的 server 与模块管理器统一编排(见 pkg/mimir/mimir.go 中 Run() 的启动流程),mux 在其中作为 Handler 被整体交给 http.Server,与上述模式一致。

中间件(Middleware)

mux 支持为 Router 添加中间件:一旦请求匹配成功,中间件会按照添加顺序依次执行,且对子路由同样生效。中间件通常是"取到一个请求,对其做一些处理,再传递给下一个中间件或最终处理器"的小块代码,常见用途包括请求日志、header 改写、ResponseWriter hijack 等。

mux 中间件使用约定俗成的标准类型定义(见 vendor/github.com/gorilla/mux/middleware.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() 将中间件加入 router:

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

更复杂的认证中间件(将 session 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(),handler 链就会停止——这正是中间件主动中止请求的手段。中间件如果要终止请求,应当写入 ResponseWriter;如果不终止请求,则不应写入。

Mimir 中的中间件实战:Mimir 在 pkg/api/handlers.go 第 288-300 行 展示了一个多层 Use() 的组合:

router := mux.NewRouter()
routeInjector := middleware.RouteInjector{RouteMatcher: router}
router.Use(routeInjector.Wrap, propagation.Middleware(extractor).Wrap)

// Use a separate metric for the querier in order to differentiate requests from the query-frontend when
// running Mimir in monolithic mode.
instrumentMiddleware := middleware.Instrument{
	Duration:         metrics.RequestDuration,
	RequestBodySize:  metrics.ReceivedMessageSize,
	ResponseBodySize: metrics.SentMessageSize,
	InflightRequests: metrics.InflightRequests,
}
router.Use(instrumentMiddleware.Wrap)

此外,Mimir 每条 HTTP 路由还有一条逐请求的中间件链,见 pkg/api/api.go 第 190-221 行 的 newRoute:

func (a *API) newRoute(path string, handler http.Handler, isPrefix, auth, gzip bool, maxBodySizeIfAny int64, methods ...string) (route *mux.Route) {
	// Propagate the consistency level on all HTTP routes.
	handler = propagation.Middleware(&querierapi.ConsistencyExtractor{}).Wrap(handler)

	if auth {
		handler = a.AuthMiddleware.Wrap(handler)
	}
	if gzip {
		handler = gziphandler.GzipHandler(handler, a.cfg.GzipCompressionLevel)
	}

	if a.activityTracker != nil && maxBodySizeIfAny > 0 {
		handler = NewActivityTrackingMiddleware(a.activityTracker, a.logger, handler)
	}

	if maxBodySizeIfAny > 0 {
		handler = newMaxBodySizeHandler(handler, maxBodySizeIfAny)
	}

	if isPrefix {
		route = a.server.HTTP.PathPrefix(path)
	} else {
		route = a.server.HTTP.Path(path)
	}
	if len(methods) > 0 {
		route = route.Methods(methods...)
	}
	route = route.Handler(handler)

	return route
}

这段代码把"README 讲的三个要点"完整落地了:Path/PathPrefix 路由匹配、Methods 方法限定、以及层层包裹的 handler 中间件链(一致性级别传播 → 租户鉴权 → gzip 压缩 → 活动跟踪 → 请求体大小限制)。

处理 CORS 请求

CORSMethodMiddleware 旨在更方便地严格设置 Access-Control-Allow-Methods 响应头:

  • 其他 CORS 头(如 Access-Control-Allow-Origin)仍需你自己的 CORS handler 设置;
  • 中间件会把路由上所有方法匹配器(例如 r.Methods(http.MethodGet, http.MethodPut, http.MethodOptions))设置为 Access-Control-Allow-Methods 的值(即 GET,PUT,OPTIONS);
  • 如果路由上没有指定任何方法,则必须有一个 OPTIONS 方法匹配器,中间件才会设置该头。

配合自定义 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 localhost:8080/foo -v 请求 /foo,响应形如:

< 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
<
foo

测试处理器

在 Go Web 应用中测试处理器十分直接,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)
    }
}

当路由带有变量时,可以把变量传入请求路径。例如注册了 /metrics/{type} 的路由后:

// 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)
        }
    }
}

Mimir 自身大量采用这种"测试内新建 mux.NewRouter() 再 ServeHTTP 到 httptest.ResponseRecorder"的模式,例如 pkg/ruler/api_test.go 与 pkg/alertmanager/api_test.go 第 1115 行 中均可看到 router := mux.NewRouter() 配合 httptest 的写法,验证了 README 所述测试范式在大型项目中的可复用性。

完整示例

一个完整可运行的 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))
}

Mimir 中 Router 的创建位置:从源码结构看全局

把前文线索串起来,可以在仓库中确认 Mimir 对 mux 的整体使用方式:

  1. 根路由的创建:在 pkg/mimir/mimir.go 第 1075 行,Mimir 构造函数中直接 mimir.Cfg.Server.Router = mux.NewRouter(),即整个进程共享一个 mux Router 作为 dskit server 的路由器;
  2. 前缀子路由:dskit server 会把所有路由注册到以 server.path-prefix 为根的子路由上,因此 Mimir 注册静态资源时需要 http.StripPrefix(a.cfg.ServerPrefix, ...) 来剥离前缀(pkg/api/api.go 第 280 行);
  3. 路由注册统一入口:pkg/api/api.go 中的 RegisterRoute/RegisterRoutesWithPrefix 负责拼接中间件链并生成 mux.Route(Path + Methods + Handler);
  4. 变量取值:各业务模块通过 mux.Vars(r) 取出 {tenant}、{block}、{user} 等路径变量(如 pkg/compactor/block_upload.go 第 203 行);
  5. 辅助开关:Mimir 还调用 s.HTTP.UseEncodedPath()(pkg/api/api.go 第 118-120 行)以保证规则 API 使用编码后的路径。对应到 vendored 源码,routeConf 结构中的 useEncodedPath 字段注释写道:"If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to""(见 vendor/github.com/gorilla/mux/mux.go 第 75-97 行);
  6. 错误语义:vendored 源码定义了 ErrMethodMismatch("method is not allowed")与 ErrNotFound("no matching route was found")两个哨兵错误(vendor/github.com/gorilla/mux/mux.go 第 16-22 行),配合 Router.NotFoundHandler/MethodNotAllowedHandler 两个可配置 handler,可实现自定义 404/405 响应。

小结

gorilla/mux 为 Mimir 提供了从路径变量、前缀子路由、方法限定到中间件链的完整路由能力,而 Mimir 的 pkg/api 又在其上叠加了租户鉴权、gzip、活动跟踪与请求体限制等中间件,形成生产级 HTTP API 的处理骨架。README 中"匹配器可自由组合、子路由先于内层路由测试、注册顺序决定优先级、不推进 next.ServeHTTP 即可中断链"这几条规则,在 Mimir 的路由注册与测试代码中都有清晰的对应,是理解该库(以及 Mimir HTTP API 行为)的关键。

本文基于仓库 vendored 的 gorilla/mux v1.8.1 文档(vendor/github.com/gorilla/mux/README.md)与其源码,Mimir 侧引用路径包括 pkg/api/api.go、pkg/api/handlers.go、pkg/mimir/mimir.go、pkg/compactor/block_upload.go 及 vendor/github.com/gorilla/mux/ 目录,均可在仓库中直接查证。

登录后查看全文
mimir