Skip to content

Commit 6c9e3d5

Browse files
committed
Merge pull request go-kit#96 from go-kit/endpoint-chain
Adaptation of @shore's proposal from go-kit#95
2 parents 41ea8e7 + 002eaaa commit 6c9e3d5

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

endpoint/endpoint.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,15 @@ var ErrBadCast = errors.New("bad cast")
1919

2020
// ContextCanceled indicates the request context was canceled.
2121
var ErrContextCanceled = errors.New("context canceled")
22+
23+
// Chain is a helper function for composing middlewares. Requests will
24+
// traverse them in the order they're declared. That is, the first middleware
25+
// is treated as the outermost middleware.
26+
func Chain(outer Middleware, others ...Middleware) Middleware {
27+
return func(next Endpoint) Endpoint {
28+
for i := len(others) - 1; i >= 0; i-- { // reverse
29+
next = others[i](next)
30+
}
31+
return outer(next)
32+
}
33+
}

endpoint/endpoint_example_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package endpoint_test
2+
3+
import (
4+
"fmt"
5+
6+
"golang.org/x/net/context"
7+
8+
"github.com/go-kit/kit/endpoint"
9+
)
10+
11+
func ExampleChain() {
12+
e := endpoint.Chain(
13+
annotate("first"),
14+
annotate("second"),
15+
annotate("third"),
16+
)(myEndpoint)
17+
18+
if _, err := e(ctx, req); err != nil {
19+
panic(err)
20+
}
21+
22+
// Output:
23+
// first pre
24+
// second pre
25+
// third pre
26+
// my endpoint!
27+
// third post
28+
// second post
29+
// first post
30+
}
31+
32+
var (
33+
ctx = context.Background()
34+
req = struct{}{}
35+
)
36+
37+
func annotate(s string) endpoint.Middleware {
38+
return func(next endpoint.Endpoint) endpoint.Endpoint {
39+
return func(ctx context.Context, request interface{}) (interface{}, error) {
40+
fmt.Println(s, "pre")
41+
defer fmt.Println(s, "post")
42+
return next(ctx, request)
43+
}
44+
}
45+
}
46+
47+
func myEndpoint(context.Context, interface{}) (interface{}, error) {
48+
fmt.Println("my endpoint!")
49+
return struct{}{}, nil
50+
}

0 commit comments

Comments
 (0)