2

功能完备的 Go 路由器 issue9/mux

 2 years ago
source link: https://www.oschina.net/p/issue9-mux
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

issue9/mux首页、文档和下载 - 功能完备的 Go 路由器 - OSCHINA - 中文开源技术交流社区

通过范型功能,可以很方便地实现一个自定义的路由:

type Context struct {
	R *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]
type Options = OptionsOf[HandlerFunc]

func New(name string, ms []Middleware, o ...Option)* 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, o...)
}

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

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

所有实现的路由,都支持以下功能:

  • 路由参数;
  • 支持正则表达式作为路由项匹配方式;
  • 拦截正则表达式的行为;
  • 自动生成 OPTIONS 请求处理方式;
  • 自动生成 HEAD 请求处理方式;
  • 根据路由反向生成地址;
  • 任意风格的路由,比如 discuz 这种不以 / 作为分隔符的;
  • 分组路由,比如按域名,或是版本号等;
  • CORS 跨域资源的处理;
  • 支持中间件;
  • 自动生成 OPTIONS * 请求;
  • 静态文件系统;
  • TRACE 请求方法的支持;
  • panic 处理;
展开阅读全文

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK