Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions endpoint/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,15 @@ var ErrBadCast = errors.New("bad cast")

// ContextCanceled indicates the request context was canceled.
var ErrContextCanceled = errors.New("context canceled")

// Chain is a helper function for composing middlewares. Requests will
// traverse them in the order they're declared. That is, the first middleware
// is treated as the outermost middleware.
func Chain(outer Middleware, others ...Middleware) Middleware {
return func(next Endpoint) Endpoint {
for i := len(others) - 1; i >= 0; i-- { // reverse
next = others[i](next)
}
return outer(next)
}
}
50 changes: 50 additions & 0 deletions endpoint/endpoint_example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package endpoint_test

import (
"fmt"

"golang.org/x/net/context"

"github.com/go-kit/kit/endpoint"
)

func ExampleChain() {
e := endpoint.Chain(
annotate("first"),
annotate("second"),
annotate("third"),
)(myEndpoint)

if _, err := e(ctx, req); err != nil {
panic(err)
}

// Output:
// first pre
// second pre
// third pre
// my endpoint!
// third post
// second post
// first post
}

var (
ctx = context.Background()
req = struct{}{}
)

func annotate(s string) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
fmt.Println(s, "pre")
defer fmt.Println(s, "post")
return next(ctx, request)
}
}
}

func myEndpoint(context.Context, interface{}) (interface{}, error) {
fmt.Println("my endpoint!")
return struct{}{}, nil
}