Flow一个令人愉快的微小而强大的Go的HTTP路由器

92 阅读2分钟

去年我为Go写了一个新的HTTP路由器,叫做 Flow.我一直在这个网站上和其他一些项目中使用它,我对它的工作情况非常满意,所以决定更广泛地分享它。

我使用Flow ,目的是将我最喜欢的功能从我经常使用的其他流行的路由器中集中起来。它有:

  • 一个非常小的、可读的代码库(大约160 LOC),其模式匹配逻辑类似于matryer/way
  • 类似于chi 的中间件管理 - 包括创建使用不同中间件的路由 "组 "的能力。
  • 可选的regexp支持,用于更严格的模式匹配,类似于chigorilla/mux
  • 自动处理OPTIONS 请求,如julienschmidt/httprouter
  • 自动处理HEAD 请求,如bmizerany/pat
  • 在所有的OPTIONS405 Method Not Allowed 响应上自动设置一个Allow 头,就像julienschmidt/httprouter
  • 能够在一个声明中把多个HTTP方法映射到同一个处理程序,如gorilla/mux

此外:

  • 它有一个非常小的API(见Go文档),所以没有多少东西需要学习。
  • 它被设计成能与http.Handlerhttp.HandlerFunc 和标准的Go中间件模式很好地配合。
  • 404 Not Found405 Method Not Allowed 响应的处理程序是可定制的。
  • 允许冲突的路由(例如:/posts/:idposts/new ),路由按其声明的顺序匹配。
  • 它的依赖性为零。

下面是一个快速的语法例子,如果你喜欢它的外观,你可以查看GitHub上的完整README:

mux := flow.New()

// The Use() method can be used to register middleware. Middleware declared at
// the top level will used on all routes (including error handlers and OPTIONS
// responses).
mux.Use(exampleMiddleware1)

// Routes can use multiple HTTP methods.
mux.HandleFunc("/profile/:name", exampleHandlerFunc1, "GET", "POST")

// Optionally, regular expressions can be used to enforce a specific pattern
// for a named parameter.
mux.HandleFunc("/profile/:name/:age|^[0-9]{1,3}$", exampleHandlerFunc2, "GET")

// The wildcard ... can be used to match the remainder of a request path.
// Notice that HTTP methods are also optional (if not provided, all HTTP
// methods will match the route).
mux.Handle("/static/...", exampleHandler)

// You can create route 'groups'.
mux.Group(func(mux *flow.Mux) {
    // Middleware declared within in the group will only be used on the routes
    // in the group.
    mux.Use(exampleMiddleware2)

    mux.HandleFunc("/admin", exampleHandlerFunc3, "GET")

    // Groups can be nested.
    mux.Group(func(mux *flow.Mux) {
        mux.Use(exampleMiddleware3)

        mux.HandleFunc("/admin/passwords", exampleHandlerFunc4, "GET")
    })
})

关于性能的说明

我没有对其他路由器做任何基准测试,所以我不能谈论Flow 的相对性能。我可以说,到目前为止,它对我所有的用例来说已经足够快了,而且在负载下对我的应用程序进行分析时也不是一个热点。