-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
37 lines (31 loc) · 1.14 KB
/
middleware.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
package outgoing
import (
"context"
"net/http"
)
type Invoker func(ctx context.Context, req *http.Request, cli *http.Client) (*http.Response, error)
type Middleware func(ctx context.Context, req *http.Request, cli *http.Client, invoker Invoker) (*http.Response, error)
func chainMiddlewares(middlewares ...Middleware) Middleware {
var chainedInt Middleware
if len(middlewares) == 0 {
chainedInt = nil
} else if len(middlewares) == 1 {
chainedInt = middlewares[0]
} else {
chainedInt = func(ctx context.Context, req *http.Request, cli *http.Client, invoker Invoker) (*http.Response, error) {
return middlewares[0](ctx, req, cli, getInvoker(middlewares, 0, invoker))
}
}
return chainedInt
}
func getInvoker(interceptors []Middleware, curr int, finalInvoker Invoker) Invoker {
if curr == len(interceptors)-1 {
return finalInvoker
}
return func(ctx context.Context, req *http.Request, cli *http.Client) (*http.Response, error) {
return interceptors[curr+1](ctx, req, cli, getInvoker(interceptors, curr+1, finalInvoker))
}
}
func invoke(_ context.Context, req *http.Request, cli *http.Client) (*http.Response, error) {
return cli.Do(req)
}