iris HTTP 路由

 

1. Handler

Handler 是一个用于处理 HTTP 请求的函数。我们可以通过 Context.Request() 获得的请求数据,然后把响应头和数据写入 Context.ResponseWriter(),最后返回请求完成的的信号。

// 在请求完成之后是不能使用上下文的。
// 取决于 HTTP 客户端软件,HTTP 协议版本,以及任何客户端和
// 服务器之间的中间件,在写入 context.ResponseWriter() 之后可能无
// 法从 Context.Request().Body 读取内容。
// 严谨的处理程序应该首先读取 Context.Request().Body ,然后再响应。
//
// 除了读取请求体,处理程序不应该更改修改提供的上下文。
//
// 如果处理程序崩溃掉,服务器任务崩溃只是影响了当前的请求。
// 恢复之后,记录错误日志中然后挂断连接。
type Handler func(Context)

一旦处理程序被注册,我们就可以使用返回的 实例为处理程序注册命名,以便在代码或模板中更容易查找。

 

2. API

所有的 HTTP 方法都支持,开发者可以为相同路径的处理程序注册不同的方法。

第一个参数是 HTTP 方法,第二个参数是路由路径,第三个可变参数应该包含一个或者多个 iris.Handler,当获取某个资源的请求从服务器到来时,处理器按照注册顺序被调用执行。

示例代码:

app := iris.New()

app.Handle("GET", "/contact", func(ctx iris.Context) {
    ctx.HTML("<h1> Hello from /contact </h1>")
})

为了让开发者更容易开发处理程序,iris 提供了所有的 HTTP 方法。第一个参数是路由路径,第二个可变参数是一个或者多个 iris.Handler。

示例代码:

app := iris.New()

// 方法: "GET"
app.Get("/", handler)

// 方法: "POST"
app.Post("/", handler)

// 方法: "PUT"
app.Put("/", handler)

// 方法: "DELETE"
app.Delete("/", handler)

// 方法: "OPTIONS"
app.Options("/", handler)

// 方法: "TRACE"
app.Trace("/", handler)

// 方法: "CONNECT"
app.Connect("/", handler)

// 方法: "HEAD"
app.Head("/", handler)

// 方法: "PATCH"
app.Patch("/", handler)

// 用于所有 HTTP 方法
app.Any("/", handler)

func handler(ctx iris.Context){
    ctx.Writef("Hello from method: %s and path: %s", ctx.Method(), ctx.Path())
}

 

3. 路由分组

一组路由可以用前缀路径分组,组之间共享相同的中间件和模板布局,组内可以嵌套组。

.Party 被用于分组路由,开发者可以声明不限数量的分组。

示例代码:

app := iris.New()

users := app.Party("/users", myAuthMiddlewareHandler)

// http://localhost:8080/users/42/profile
users.Get("/{id:int}/profile", userProfileHandler)
// http://localhost:8080/users/messages/1
users.Get("/messages/{id:int}", userMessageHandler)

同样可以这样写,使用一个接受子路由的函数:

app := iris.New()

app.PartyFunc("/users", func(users iris.Party) {
    users.Use(myAuthMiddlewareHandler)

    // http://localhost:8080/users/42/profile
    users.Get("/{id:int}/profile", userProfileHandler)
    // http://localhost:8080/users/messages/1
    users.Get("/messages/{id:int}", userMessageHandler)
})

id:int 是一个带类型的动态路径参数。

上下文 iris.Context 是服务器用于所有客户端的中间人 "对象"。 对于每一个新的连接,会从 sync.Pool 中获取一个新上下文对象。上下文 iris.Context 是 iris 的 htt ...