Handler原理解析
###Handler含义 一句话:主要作用是解析请求url,跳转到指定controller函数中,完成后台逻辑。
Handler 接口
在需要实现Handler时,必须实现Handler接口
type Handler interface {
Serve(*Context)
}
一旦Handler被注册了,我们就可以用RouteNameFunc函数给注册的Handler来实现一一关联
说了这么多,太绕了,看例子讲解
type myHandlerGet struct {
}
func (m myHandlerGet) Serve(ctx *iris.Context) {
ctx.Writef("From %s", ctx.Path())
}
例子中我们写了一个myHandlerGet并且实现了Handler接口,所以我们就可以注册使用它了
iris.Handle("GET", "/get", myHandlerGet{})
请求localhost:8080/get,会执行myHandlerGet.Server(),最后返回From localhost:8080/get
HandlerFuncs函数
HandlerFuncs必须实现Handler接口中的Server(Context)函数。HandlerFuncs是注册Handler最简单的中间件
type HandlerFunc func(*Context)
func (h HandlerFunc) Serve(c *Context) {
h(c)
}
这里不同的是HandlerFunc必须是一个函数,一个实现了Handler接口的函数
func handlerFuncTest(ctx *iris.Context) {
ctx.Writef("Hello")
}
iris.HandleFunc("GET","/letsgetit",handlerFuncTest)
//或者直接调用
iris.Get("/letsgetit", handlerFuncTest)
iris.Post("/letspostit", handlerFuncTest)
iris.Put("/letputit", handlerFuncTest)
iris.Delete("/letsdeleteit", handlerFuncTest)
iris中的Handler实例应用
写法一
// 注册Handler和
iris.Get("/", Index)
iris.Get("/about", About)
func Index(ctx *iris.Context){
ctx.Render("index.html", nil)
}
func About(ctx *iris.Context){
ctx.MustRender("about.html", nil)
}
先看一下iris.Get函数
func (api Framework) Get(path string, handlersFn ...HandlerFunc) RouteNameFunc
- Get函数就是前面说的Handler,它内部实现了Handler接口。
path参数就是路径,即网址请求的地址。handlersFn参数就是对应要用到的函数。- 例子中是当输入
localhost:8080/后会直接进入Index函数中执行,最后返回index.html页面
写法二
// define a function
test := func(ctx *iris.Context) {
ctx.Render("index.html", nil)
}
// handler registration and naming
iris.Get("/", test)("home")
iris.Get("/about", test)("about")
iris.Get("/page/:id", test)("page")
iris.Get()返回的是一个RouteNameFunc而这个函数的原型是
type RouteNameFunc func(customRouteName string) Route
所以我们可以传入自定义的RouteName作为标识,其实这些(“home”、“about”、“page”)并没有什么实质的意义。
这两种不同的写法对比着看一下大家就知道了,我推荐的是第一种写法,这样在大的实战项目中对整体架构有一定的帮助
到此对Handler怎么执行大概有了一个概念。 还有什么疑问可以留言,看到第一时间回复。