# Handler抽象

在上一章节中,我们新增了handler并且基于map实现了我们的简单路由。我们看看以Server中的Route函数:

func (S *SDKHTTPServer) Route(
	method string, //
	pattern string,
	handleFunc func(*Context)) {
	S.handler.handlers[S.key(method, pattern)] = handleFunc
}
1
2
3
4
5
6

我们可以看到我们直接访问了 handler的属性,并设置了值,实际上这样写是不太好的,我们可以尝试将这部分依赖接口,而不是依赖具体的细节。

# 组合实现接口

我们的handler中已经实现了http.Handler的接口,在这个基础上我们还想要有一个自己的接口,但是这个接口需要实现http.Handler这个接口。在go中,我们通常使用组合的方式实现。

type Handler interface {
	http.Handler
	Route(method string, pattern string, handleFunc func(*Context))
}
1
2
3
4

HandlerBaseOnMap需要实现Route以实现Handler接口

func (h *HandlerBaseOnMap) Route(
	method string,
	pattern string,
	handleFunc func(*Context)) {
	h.handlers[h.key(method, pattern)] = handleFunc
}
1
2
3
4
5
6

# Server端

为了不让Server依赖细节,可以在让Handler接口实现Route方法,让Server直接委托即可,此时Server的代码:

func (S *SDKHTTPServer) Route(
	method string,
	pattern string,
	handleFunc func(*Context)) {
	S.handler.Route(method, pattern, handleFunc)
}
1
2
3
4
5
6

这也是我们常用的重构的移动的方式,将方法或类移动到其逻辑上更合适的位置。

其他修改:

func NewServer(name string) Server {
	return &SDKHTTPServer{
		Name: name,
		handler: NewHandlerBaseOnMap(), // 使用简单创建函数即可,不依赖细节
	}
}

type SDKHTTPServer struct {
	Name string
	handler Handler  // handler 依赖接口即可
}
1
2
3
4
5
6
7
8
9
10
11

# Route接口

通过上面修改,我们发现Route即存在在Handler中,也存在在Server中,这两个是委托关系,参数都是一致的,其实也可以抽象成接口。于是我们把Route也抽象出来:

type RouteAble interface{
	Route(method string, pattern string, handleFunc func(*Context))
}
1
2
3

Handler接口:

type Handler interface {
	http.Handler
	RouteAble
}
1
2
3
4

Server接口:

type Server interface {
	RouteAble
	Start(port string) error
}
1
2
3
4
上次更新: 10/9/2023,