ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
### 路由 路由可以通过特定的 HTTP 方法,url 路径和一个匹配的 handler 来注册。例如,下面的代码则展示了一个注册路由的例子,访问方式为 Get,访问路径为 /hello,处理结果是返回输出 Hello World 的响应。 ~~~ // 业务处理 func hello(ctx dotweb.Context) error { ctx.WriteString("Hello, World!") return nil } // 路由 app.HttpServer.GET("/hello", hello) ~~~ 特别的,你可以用 DotWeb.HttpServer.Any(path string, handle HttpHandle) 来为所有的 HTTP 方法发送注册 handler; * 支持GET\POST\HEAD\OPTIONS\PUT\PATCH\DELETE 这几类请求方法 * 支持HiJack\WebSocket\ServerFile三类特殊应用 * 支持Any注册方式,默认兼容GET\POST\HEAD\OPTIONS\PUT\PATCH\DELETE方式 * 支持通过配置开启默认添加HEAD方式 * 支持注册Handler,以启用配置化 * 支持检查请求与指定路由是否匹配 #### 静态路由 静态路由语法就是没有任何参数变量,pattern是一个固定的字符串。 ~~~ package main import ( "github.com/devfeel/dotweb" ) func main() { app := dotweb.New() app.HttpServer.GET("/hello", func(ctx dotweb.Context) error{ return ctx.WriteString("hello world!") }) app.StartServer(80) } ~~~ test: curl http://127.0.0.1/hello #### 参数路由 参数路由以冒号 : 后面跟一个字符串作为参数名称,可以通过 HttpContext的 GetRouterName 方法获取路由参数的值。 ~~~ package main import ( "github.com/devfeel/dotweb" ) func main() { app := dotweb.New() app.HttpServer.GET("/hello/:name", func(ctx dotweb.Context) error{ return ctx.WriteString("hello " + ctx.GetRouterName("name")) }) app.HttpServer.GET("/news/:category/:newsid", func(ctx dotweb.Context) error{ category := ctx.GetRouterName("category") newsid := ctx.GetRouterName("newsid") return ctx.WriteString("news info: category=" + category + " newsid=" + newsid) }) app.StartServer(80) } ~~~ test: curl http://127.0.0.1/hello/devfeel curl http://127.0.0.1/news/category1/1 #### 组路由 DotWeb.HttpServer.Group(prefix string) Group 拥有相同前缀的路由可以通过中间件定义一个子路由来化为一组。 组路由也会继承父中间件。 在组路由里使用中间件可以用Group.Use(m ...Middleware)。 下面的代码,我们创建了一个 admin 组,使所有的 /admin/* 都会执行accesslog中间件,并为其添加index路由,访问地址为:/admin/index ~~~ import "github.com/devfeel/middleware/accesslog" g := app.HttpServer.Group("/admin") g.Use(accesslog.Middleware()) g.Get("/index", func(ctx dotweb.Context) error { ctx.WriteString("/admin/index") return nil }) ~~~ test: curl http://127.0.0.1/admin/index