Skip to content

Commit ebd9ae3

Browse files
committed
feat: add validate interceptor
1 parent db8f735 commit ebd9ae3

File tree

3 files changed

+38
-1
lines changed

3 files changed

+38
-1
lines changed

interceptor/kvalidate/validate.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package kvalidate
2+
3+
import (
4+
"context"
5+
"fmt"
6+
7+
"github.com/go-kod/kod"
8+
"github.com/go-playground/validator/v10"
9+
)
10+
11+
// Interceptor returns a interceptor that validates the call specified by info.
12+
func Interceptor() kod.Interceptor {
13+
validate := validator.New()
14+
15+
return func(ctx context.Context, info kod.CallInfo, req, reply []any, invoker kod.HandleFunc) error {
16+
for _, v := range req {
17+
if err := validate.Struct(v); err != nil {
18+
return fmt.Errorf("validate failed: %w", err)
19+
}
20+
}
21+
22+
return invoker(ctx, info, req, reply)
23+
}
24+
}

tests/case1/case.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
"github.com/go-kod/kod/interceptor/krecovery"
1717
"github.com/go-kod/kod/interceptor/ktimeout"
1818
"github.com/go-kod/kod/interceptor/ktrace"
19+
"github.com/go-kod/kod/interceptor/kvalidate"
1920
"github.com/samber/lo"
2021
"go.opentelemetry.io/otel"
2122
"go.opentelemetry.io/otel/baggage"
@@ -73,6 +74,7 @@ func (t *test1Component) Interceptors() []kod.Interceptor {
7374
kratelimit.Interceptor(),
7475
kaccesslog.Interceptor(),
7576
kcircuitbreaker.Interceptor(),
77+
kvalidate.Interceptor(),
7678
ktimeout.Interceptor(ktimeout.WithTimeout(time.Second)),
7779
}
7880
}
@@ -82,7 +84,7 @@ func (t *test1Component) Stop(ctx context.Context) error {
8284
}
8385

8486
type FooReq struct {
85-
Id int
87+
Id int `validate:"lt=100"`
8688
Panic bool
8789
}
8890

tests/case1/case_test.go

+11
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,17 @@ func TestInterfacePanic(t *testing.T) {
7272
})
7373
}
7474

75+
func TestInterfacValidate(t *testing.T) {
76+
t.Parallel()
77+
kod.RunTest(t, func(ctx context.Context, k Test1Component) {
78+
79+
_, err := k.Foo(ctx, &FooReq{
80+
Id: 101,
81+
})
82+
assert.Contains(t, err.Error(), "validate failed: Key: 'FooReq.Id' Error:Field validation for 'Id' failed on the 'lt' tag")
83+
})
84+
}
85+
7586
func TestFake(t *testing.T) {
7687
t.Parallel()
7788
fakeTest1 := &fakeTest1Component{"B"}

0 commit comments

Comments
 (0)