Go语言-技巧之接口函数

基本定义

定义:接口函数顾名思义,他本身是一个函数,但是实现了一个接口,在这个接口中自己调用自己。
使用场景:适用于接口里只有一个函数的场景
作用:面向接口编程有时候我们为了适配不通的场景,往往需要实现多个接口,这样就会凭空出现很多接口的实现者。如果我们用接口函数就可以很好的规避这一点。
命名规范:在接口名称后面加上Func,比如接口是KeyHandler,接口函数就是KeyHandlerFunc

Show Code

我最早接触的接口函数就是http.handlerFunc,它实现了接口Handler,见下面代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}

// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}

我们更多的将它作为接口的拦截器用。这时候会有俩种用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

//第一种. 采用了接口函数,我们只需要实现一个func(w http.ResponseWriter, r *http.Request),并且强转成http.HandlerFunc
func AuthInterceptor(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//...before
next.ServeHTTP(w, r)//业务逻辑
//...after
})
}

//第二种. 不采用接口函数,这时候你要显示的定义AuthLogic实现http.Handler接口,我们程序中会多出来很多AuthLogic这种结构体
func AuthInterceptor(next http.Handler) http.Handler {
return AuthLogic{next:next}
}

type AuthLogic struct {
next http.Handler
}

func (a AuthLogic) ServeHTTP(w http.ResponseWriter, r *http.Request) {
//...before
a.next.ServeHTTP(w, r)
//...after
}

所以函数接口让我们的接口调用更加的简便灵活。