github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/go-grpc-middleware/validator/doc.go (about)

     1  // Copyright 2016 Michal Witkowski. All Rights Reserved.
     2  // See LICENSE for licensing terms.
     3  
     4  /*
     5  `grpc_validator` is a generic request contents validator server-side middleware for gRPC.
     6  
     7  Request Validator Middleware
     8  
     9  Validating input is important, and hard. It also causes a lot of boilerplate code. This middleware
    10  checks for the existence of a `Validate` method on each of the messages of a gRPC request. This
    11  includes the single request of the `Unary` calls, as well as each message of the inbound Stream calls.
    12  In case of a validation failure, an `InvalidArgument` gRPC status is returned, along with a
    13  description of the validation failure.
    14  
    15  While it is generic, it was intended to be used with https://github.com/mwitkow/go-proto-validators,
    16  a Go protocol buffers codegen plugin that creates the `Validate` methods (including nested messages)
    17  based on declarative options in the `.proto` files themselves. For example:
    18  
    19  
    20  	syntax = "proto3";
    21  	package validator.examples;
    22  	import "github.com/mwitkow/go-proto-validators/validator.proto";
    23  
    24  	message InnerMessage {
    25  	  // some_integer can only be in range (1, 100).
    26  	  int32 some_integer = 1 [(validator.field) = {int_gt: 0, int_lt: 100}];
    27  	  // some_float can only be in range (0;1).
    28  	  double some_float = 2 [(validator.field) = {float_gte: 0, float_lte: 1}];
    29  	}
    30  
    31  	message OuterMessage {
    32  	  // important_string must be a lowercase alpha-numeric of 5 to 30 characters (RE2 syntax).
    33  	  string important_string = 1 [(validator.field) = {regex: "^[a-z]{2,5}$"}];
    34  	  // proto3 doesn't have `required`, the `msg_exist` enforces presence of InnerMessage.
    35  	  InnerMessage inner = 2 [(validator.field) = {msg_exists : true}];
    36  	}
    37  
    38  The `OuterMessage.Validate` would include validation of regexes, existence of the InnerMessage and
    39  the range values within it. The `grpc_validator` middleware would then automatically use that to
    40  check all messages processed by the server.
    41  
    42  Please consult https://github.com/mwitkow/go-proto-validators for details on `protoc` invocation and
    43  other parameters of customization.
    44  */
    45  package grpc_validator