Skip to content

Commit d0b7cac

Browse files
committed
feat: add generics to the endpoint layer
Signed-off-by: Mark Sagi-Kazar <[email protected]>
1 parent d7f6bac commit d0b7cac

File tree

2 files changed

+11
-11
lines changed

2 files changed

+11
-11
lines changed

endpoint/endpoint.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,20 @@ import (
66

77
// Endpoint is the fundamental building block of servers and clients.
88
// It represents a single RPC method.
9-
type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error)
9+
type Endpoint[Req any, Resp any] func(ctx context.Context, request Req) (response Resp, err error)
1010

1111
// Nop is an endpoint that does nothing and returns a nil error.
1212
// Useful for tests.
1313
func Nop(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil }
1414

1515
// Middleware is a chainable behavior modifier for endpoints.
16-
type Middleware func(Endpoint) Endpoint
16+
type Middleware[Req any, Resp any] func(Endpoint[Req, Resp]) Endpoint[Req, Resp]
1717

1818
// Chain is a helper function for composing middlewares. Requests will
1919
// traverse them in the order they're declared. That is, the first middleware
2020
// is treated as the outermost middleware.
21-
func Chain(outer Middleware, others ...Middleware) Middleware {
22-
return func(next Endpoint) Endpoint {
21+
func Chain[Req any, Resp any](outer Middleware[Req, Resp], others ...Middleware[Req, Resp]) Middleware[Req, Resp] {
22+
return func(next Endpoint[Req, Resp]) Endpoint[Req, Resp] {
2323
for i := len(others) - 1; i >= 0; i-- { // reverse
2424
next = others[i](next)
2525
}

endpoint/endpoint_example_test.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ import (
99

1010
func ExampleChain() {
1111
e := endpoint.Chain(
12-
annotate("first"),
13-
annotate("second"),
14-
annotate("third"),
12+
annotate[any, any]("first"),
13+
annotate[any, any]("second"),
14+
annotate[any, any]("third"),
1515
)(myEndpoint)
1616

1717
if _, err := e(ctx, req); err != nil {
@@ -33,13 +33,13 @@ var (
3333
req = struct{}{}
3434
)
3535

36-
func annotate(s string) endpoint.Middleware {
37-
return func(next endpoint.Endpoint) endpoint.Endpoint {
38-
return func(ctx context.Context, request interface{}) (interface{}, error) {
36+
func annotate[Req any, Resp any](s string) endpoint.Middleware[Req, Resp] {
37+
return func(next endpoint.Endpoint[Req, Resp]) endpoint.Endpoint[Req, Resp] {
38+
return endpoint.Endpoint[Req, Resp](func(ctx context.Context, request Req) (Resp, error) {
3939
fmt.Println(s, "pre")
4040
defer fmt.Println(s, "post")
4141
return next(ctx, request)
42-
}
42+
})
4343
}
4444
}
4545

0 commit comments

Comments
 (0)