validate.go 989 B

12345678910111213141516171819202122232425262728293031
  1. package warden
  2. import (
  3. "context"
  4. "go-common/library/ecode"
  5. "google.golang.org/grpc"
  6. "gopkg.in/go-playground/validator.v9"
  7. )
  8. var validate = validator.New()
  9. // Validate return a client interceptor validate incoming request per RPC call.
  10. func (s *Server) validate() grpc.UnaryServerInterceptor {
  11. return func(ctx context.Context, req interface{}, args *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
  12. if err = validate.Struct(req); err != nil {
  13. err = ecode.RequestErr
  14. return
  15. }
  16. resp, err = handler(ctx, req)
  17. return
  18. }
  19. }
  20. // RegisterValidation adds a validation Func to a Validate's map of validators denoted by the key
  21. // NOTE: if the key already exists, the previous validation function will be replaced.
  22. // NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation
  23. func (s *Server) RegisterValidation(key string, fn validator.Func) error {
  24. return validate.RegisterValidation(key, fn)
  25. }