处理器
处理器(Handler)负责处理请求并返回响应。常规设置方法如下:
go
package main
import (
"net/http"
"github.com/cquestor/gone"
)
func HelloHandler(ctx *gone.Context) gone.IResponse {
return gone.String(http.StatusOK, "Hello!\n")
}
func main() {
g := gone.New()
g.Get("/hello", HelloHandler)
g.Run()
}
所有的处理器都要实现IHandler接口,IHandler的结构如下:
go
type IHandler interface {
Do(ctx *Context) IResponse
}
如你所见,IHandler只有一个Do方法,它接收请求的上下文作为参数,并返回一个响应接口。在接收到用户请求后,相应处理器的Do方法会被调用,如果响应不为nil的话,该响应会被执行。
处理器可以作为路由绑定,也可以作为中间件,两者的结构类型相同。在处理请求时,多个处理器会按顺序执行,直到某个处理器返回了非nil的响应。
CQuestor