### 路由
路由可以通過特定的 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