You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.2 KiB
Go
43 lines
1.2 KiB
Go
package builtin
|
|
|
|
import (
|
|
ctxpkg "github.com/noahlann/nnet/pkg/context"
|
|
interceptorpkg "github.com/noahlann/nnet/pkg/interceptor"
|
|
)
|
|
|
|
// ValidationInterceptor 验证拦截器
|
|
func ValidationInterceptor(validator func(data []byte, ctx ctxpkg.Context) error) interceptorpkg.Interceptor {
|
|
return interceptorpkg.HandlerFunc(func(data []byte, ctx ctxpkg.Context, next interceptorpkg.Chain) ([]byte, bool, error) {
|
|
if validator == nil {
|
|
return next.Next(data, ctx)
|
|
}
|
|
|
|
if err := validator(data, ctx); err != nil {
|
|
return nil, false, err
|
|
}
|
|
|
|
return next.Next(data, ctx)
|
|
})
|
|
}
|
|
|
|
// MinLengthInterceptor 最小长度验证拦截器
|
|
func MinLengthInterceptor(minLength int) interceptorpkg.Interceptor {
|
|
return ValidationInterceptor(func(data []byte, ctx ctxpkg.Context) error {
|
|
if len(data) < minLength {
|
|
return interceptorpkg.New("data too short")
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// MaxLengthInterceptor 最大长度验证拦截器
|
|
func MaxLengthInterceptor(maxLength int) interceptorpkg.Interceptor {
|
|
return ValidationInterceptor(func(data []byte, ctx ctxpkg.Context) error {
|
|
if len(data) > maxLength {
|
|
return interceptorpkg.New("data too long")
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|