-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrapper.go
49 lines (39 loc) · 1.04 KB
/
wrapper.go
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
/**
* Author: Tony.Shao
* Email: [email protected]
* Github: github.com/xiocode
* File: wrapper.go
* Description: handlers wrapper
*/
package wrapper
import (
"net/http"
"context"
)
type ContextHandler interface {
ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request)
}
type ContextHandlerFunc func(context.Context, http.ResponseWriter, *http.Request)
func (h ContextHandlerFunc) ServeHTTPContext(ctx context.Context, rw http.ResponseWriter, req *http.Request) {
h(ctx, rw, req)
}
type ContextAdapter struct {
Context context.Context
Handler ContextHandler
}
func (ca *ContextAdapter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
ca.Handler.ServeHTTPContext(ca.Context, rw, req)
}
func Handler(ctx context.Context, handler ContextHandlerFunc) *ContextAdapter {
return &ContextAdapter{
Context: ctx,
Handler: handler,
}
}
func Wrapper(handler ContextHandlerFunc) *ContextAdapter {
ctx := context.Background()
return &ContextAdapter{
Context: ctx,
Handler: handler,
}
}