05.装饰器
# 01.golang装饰器
# 1.1 简单timer装饰器
package main
import (
"fmt"
"time"
)
func timer(fn func()) func() {
return func() {
startTime := time.Now().Unix()
fn()
endTime := time.Now().Unix()
fmt.Println("运行时间:", endTime - startTime)
}
}
func testFunc() {
fmt.Println("运行 testFunc")
time.Sleep(time.Second * 2)
}
func main() {
testFunc := timer(testFunc)
testFunc()
}
/*
运行 testFunc
运行时间: 2
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 1.2 项目中认证实现
package main
import (
"fmt"
"log"
"net/http"
)
type DecoratorHandler func(http.HandlerFunc) http.HandlerFunc
func MiddlewareHandlerFunc(hp http.HandlerFunc, decors ...DecoratorHandler) http.HandlerFunc {
for _,fn := range decors {
dp := fn
hp = dp(hp) // dp(hp) => VerifyHeader(Pong)
}
return hp
}
func VerifyHeader(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token")
if token == "" {
fmt.Fprintf(w,r.URL.Path +" VerifyHeader:token不能为空")
return
}
h(w,r)
}
}
func VerifyHeader2(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("token")
if token != "mimi" {
fmt.Fprintf(w,r.URL.Path +" VerifyHeader:token必须为:mimi")
return
}
h(w,r)
}
}
func Pong(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w,r.URL.Path +"--> 验证通过,返回数据")
return
}
func main() {
// http://127.0.0.1:8080/test?token=mimi
http.HandleFunc("/test",MiddlewareHandlerFunc(Pong, VerifyHeader, VerifyHeader2))
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
上次更新: 2024/3/13 15:35:10