Categorygithub.com/issue9/mux/v6
modulepackage
6.2.0
Repository: https://github.com/issue9/mux.git
Documentation: pkg.go.dev

# README

mux

Go Go version Go Report Card license codecov PkgGoDev

mux 功能完备的 Go 路由器:

  • 路由参数;
  • 支持正则表达式作为路由项匹配方式;
  • 拦截正则表达式的行为;
  • 自动生成 OPTIONS 请求处理方式;
  • 自动生成 HEAD 请求处理方式;
  • 根据路由反向生成地址;
  • 任意风格的路由,比如 discuz 这种不以 / 作为分隔符的;
  • 分组路由,比如按域名,或是版本号等;
  • CORS 跨域资源的处理;
  • 支持中间件;
  • 自动生成 OPTIONS * 请求;
  • 静态文件系统;
  • TRACE 请求方法的支持;
  • panic 处理;
  • 支持泛型,可轻易实现自定义的路由处理方式;
import "github.com/issue9/middleware/v5/auth/basic"
import "github.com/issue9/mux/v6"

c := basic.New()

router := mux.NewRouter("", &mux.Options{}, c)
router.Get("/users/1", h).
    Post("/login", h).
    Get("/pages/{id:\\d+}.html", h). // 匹配 /pages/123.html 等格式,path = 123
    Get("/posts/{path}.html", h).    // 匹配 /posts/2020/11/11/title.html 等格式,path = 2020/11/11/title

// 统一前缀路径的路由
p := router.Prefix("/api")
p.Get("/logout", h) // 相当于 m.Get("/api/logout", h)
p.Post("/login", h) // 相当于 m.Get("/api/login", h)

// 对同一资源的不同操作
res := p.Resource("/users/{id:\\d+}")
res.Get(h)   // 相当于 m.Get("/api/users/{id:\\d+}", h)
res.Post(h)  // 相当于 m.Post("/api/users/{id:\\d+}", h)
res.URL(map[string]string{"id": "5"}) // 构建一条基于此路由项的路径:/users/5

http.ListenAndServe(":8080", router)

语法

路由参数采用大括号包含,内部包含名称和规则两部分:{name:rule}, 其中的 name 表示参数的名称,rule 表示对参数的约束规则。

name 可以包含 - 前缀,表示在实际执行过程中,不捕获该名称的对应的值, 可以在一定程序上提升性能。

rule 表示对参数的约束,一般为正则或是空,为空表示匹配任意值, 拦截器一栏中有关 rule 的高级用法。以下是一些常见的示例。

/posts/{id}.html                  // 匹配 /posts/1.html
/posts-{id}-{page}.html           // 匹配 /posts-1-10.html
/posts/{path:\\w+}.html           // 匹配 /posts/2020/11/11/title.html
/tags/{tag:\\w+}/{path}           // 匹配 /tags/abc/title.html

路径匹配规则

可能会出现多条记录与同一请求都匹配的情况,这种情况下, 系统会找到一条认为最匹配的路由来处理,判断规则如下:

  1. 普通路由优先于正则路由;
  2. 拦截器优先于正则路由;
  3. 正则路由优先于命名路由;

比如:

/posts/{id}.html              // 1
/posts/{id:\\d+}.html         // 2
/posts/1.html                 // 3

/posts/1.html      // 匹配 3
/posts/11.html     // 匹配 2
/posts/index.html  // 匹配 1

路径的匹配是以从左到右的顺序进行的,父节点不会因为没有子节点匹配而扩大自己的匹配范围, 比如 /posts/{id}-{page:digit}.html 可以匹配 /posts/1-1.html,但无法匹配 /posts/1-1-1.html,虽然理论上 1-1- 也能匹配 {id},但是 1- 已经优先匹配了, 在子元素找不到的情况下,并不会将父元素的匹配范围扩大到 1-1-

路由参数

通过正则表达式匹配的路由,其中带命名的参数可通过 GetParams() 获取:

import "github.com/issue9/mux/v6"

params := mux.GetParams(r)

id, err := params.Int("id")
 // 或是
id := params.MustInt("id", 0) // 在无法获取 id 参数时采用 0 作为默认值返回

高级用法

分组路由

可以通过匹配 Matcher 接口,定义了一组特定要求的路由项。

// server.go

import "github.com/issue9/mux/v6"
import "github.com/issue9/mux/v6/muxutil"

m := mux.NewRouters(...)

def := mux.NewRouter("default")
m.AddRouter(muxutil.NewPathVersion("version-key", "v1"), def)
def.Get("/path", h1)

host := mux.NewRouter("host")
m.AddRouter(muxutil.NewHosts("*.example.com"), host)
host.Get("/path", h2)

http.ListenAndServe(":8080", m)

// client.go

// 访问 h2 的内容
r := http.NewRequest(http.MethodGet, "https://abc.example.com/path", nil)
r.Do()

// 访问 h1 的内容
r := http.NewRequest(http.MethodGet, "https://other_domain.com/v1/path", nil)
r.Do()

拦截器

正常情况下,/posts/{id:\d+} 或是 /posts/{id:[0-9]+} 会被当作正则表达式处理, 但是正则表达式的性能并不是很好,这个时候我们可以通过在 NewRouter 传递 Interceptor 进行拦截:

import "github.com/issue9/mux/v6"

func digit(path string) bool {
    for _, c := range path {
        if c < '0' || c > '9' {
            return false
        }
    }
    return len(path) > 0
}

// 路由中的 \d+ 和 [0-9]+ 均采用 digit 函数进行处理,不再是正则表达式。
opt := mux.Options{Interceptors: map[string]mux.InterceptorFunc{"\\d+": digit, "[0-9]+": digit}
r := mux.NewRouter("", opt)

这样在所有路由项中的 [0-9]+\\d+ 将由 digit 函数处理, 不再会被编译为正则表达式,在性能上会有很大的提升。 通过该功能,也可以自定义一些非正常的正则表达这式,然后进行拦截,比如:

/posts/{id:digit}/.html

如果不拦截,最终传递给正则表达式,可能会出现编译错误,通过拦截器可以将 digit 合法化。 目前提供了以下几个拦截器:

  • InterceptorDigit 限定为数字字符,相当于正则的 [0-9]
  • InterceptorWord 相当于正则的 [a-zA-Z0-9]
  • InterceptorAny 表示匹配任意非空内容;

用户也可以自行实现 InterceptorFunc 作为拦截器。具体可参考 OptionsOf.Interceptors。

CORS

CORS 不再是以中间件的形式提供,而是通过 NewRouter 直接传递有关 CORS 的配置信息, 这样可以更好地处理每个地址支持的请求方法。

OPTIONS 请求方法由系统自动生成。

import "github.com/issue9/mux/v6"

r := mux.NewRouter("name" ,&mux.Options{CORS: AllowedCORS}) // 任意跨域请求

r.Get("/posts/{id}", nil)     // 默认情况下, OPTIONS 的报头为 GET, OPTIONS

http.ListenAndServe(":8080", m)

// client.go

// 访问 h2 的内容
r := http.NewRequest(http.MethodGet, "https://localhost:8080/posts/1", nil)
r.Header.Set("Origin", "https://example.com")
r.Do() // 跨域,可以正常访问


r = http.NewRequest(http.MethodOptions, "https://localhost:8080/posts/1", nil)
r.Header.Set("Origin", "https://example.com")
r.Header.Set("Access-Control-Request-Method", "GET")
r.Do() // 预检请求,可以正常访问

静态文件

可以使用 ServeFile 与命名参数相结合的方式实现静态文件的访问:

r := NewRouter("")
r.Get("/assets/{path}", func(w http.ResponseWriter, r *http.Request){
    err := muxutil.ServeFile(os.DirFS("/static/"), "path", "index.html", w, r)
    if err!= nil {
        http.Error(err.Error(), http.StatusInternalServerError)
    }
})

自定义路由

官方提供的 http.Handler 未必是符合每个人的要求,通过 RouterOf 用户可以很方便地实现自定义格式的 http.Handler, 只需要以下几个步骤:

  1. 定义一个专有的路由处理类型,可以是类也可以是函数;
  2. 根据此类型,生成对应的 RouterOf、PrefixOf、ResourceOf、MiddlewareFuncOf 等类型;
  3. 定义 CallOf 函数;
  4. 将 CallOf 传递给 NewOf;
type Context struct {
    *http.Request
    W http.ResponseWriter
    P Params
}

type HandlerFunc func(ctx *Context)

type Router = RouterOf[HandlerFunc]
type Prefix = PrefixOf[HandlerFunc]
type Resource = ResourceOf[HandlerFunc]
type MiddlewareFunc = MiddlewareFuncOf[HandlerFunc]
type Middleware = MiddlewareOf[HandlerFunc]

func New(name string, ms []Middleware)* Router {
    f := func(w http.ResponseWriter, r *http.Request, ps Params, h HandlerFunc) {
        ctx := &Context {
            R: r,
            W: w,
            P: ps,
        }
        h(ctx)
    }
    return NewRouterOf[HandlerFunc](name, f, ms...)
}

以上就是自定义路由的全部功能,之后就可以直接使用:

r := New("router", nil)

r.Get("/path", func(ctx *Context){
    // TODO
    ctx.W.WriteHeader(200)
})

r.Prefix("/admin").Get("/login", func(ctx *Context){
    // TODO
    ctx.W.WriteHeader(501)
})

更多自定义路由的介绍可参考 https://caixw.io/posts/2022/build-go-router-with-generics.html

性能

https://caixw.github.io/go-http-routers-testing/ 提供了与其它几个框架的对比情况。

版权

本项目采用 MIT 开源授权许可证,完整的授权说明可在 LICENSE 文件中找到。

# Packages

Package muxutil 为 mux 提供的一些额外工具.
Package params 路由参数的相关声明.
Package routertest 提供针对路由的测试用例 NOTE: 只提供针对不同的类型参数 T 可能造成不周结果的测试。.

# Functions

AllowedCORS 允许跨域请求.
CheckSyntax 检测路由项的语法格式.
DefaultCall 针对 http.Handler 的 CallOf 实现.
GetParams 获取当前请求实例上的参数列表 NOTE: 仅适用于 Router 而不是所有 RouterOf。.
HTTPRecovery 仅向客户端输出 status 状态码.
InterceptorAny 任意非空字符的拦截器.
InterceptorDigit 任意数字字符的拦截器.
InterceptorWord 任意英文单词的拦截器.
LogRecovery 将错误信息输出到日志 status 表示向客户端输出的状态码; l 为输出的日志;.
Methods 返回所有支持的请求方法.
No description provided by the author
NewRouter 声明适用于官方 http.Handler 接口的路由 这是对 NewRouterOf 的实例化,相当于 NewRouterOf[http.Handler]。.
NewRouterOf 声明路由 name string 路由名称,可以为空; o 修改路由的默认形为。比如 CaseInsensitive 会让路由忽略大小写,可以为空。 T 表示用户用于处理路由项的方法,该类型最终通过 NewRouterOf 中的 call 参数与 http.ResponseWriter 和 *http.Request 相关联。.
No description provided by the author
NewRoutersOf 声明一个新的 RoutersOf notFound 表示所有路由都不匹配时的处理方式,如果为空,则调用 http.NotFoundHandler。.
URL 根据参数生成地址 pattern 为路由项的定义内容; params 为路由项中的参数,键名为参数名,键值为参数值。 NOTE: 仅仅是将 params 填入到 pattern 中, 不会判断参数格式是否正确。.
WithValue 将参数 ps 附加在 r 上 与 context.WithValue 功能相同,但是考虑了在同一个 r 上调用多次 WithValue 的情况。 NOTE: 仅适用于 Router 而不是所有 RouterOf。.
WriterRecovery 向 io.Writer 输出错误信息 status 表示向客户端输出的状态码; out 输出的 io.Writer,比如 os.Stderr 等;.

# Structs

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Interfaces

No description provided by the author
No description provided by the author

# Type aliases

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Params 路由参数.
No description provided by the author