Validate

    First you should install proto-gen-validate

    Example

    Here are some examples of parameter validation for several common situations, you may also refer to more examples in proto-gen-validate

    1. // id must be greater than 0
    2. // age must be in the range (0, 120]
    3. int32 age = 2 [(validate.rules).int64 = {gt:0, lte: 120}];
    4. // code must be either 1, 2, or 3
    5. uint32 code = 3 [(validate.rules).uint32 = {in: [1,2,3]}];
    6. // score cannot be 0 nor 0.99
    7. float score = 1 [(validate.rules).float = {not_in: [0, 99.99]}];

    Bools

    1. bool state = 5 [(validate.rules).bool.const = true];
    2. // x cannot be set to true
    3. bool state = 5 [(validate.rules).bool.const = false];

    Strings

    Messages

    1. // info cannot be unset
    2. Info info = 11 [(validate.rules).message.required = true];
    3. string address = 1;
    4. }

    Code Generation

    1. protoc --proto_path=. \
    2. --go_out=paths=source_relative:. \
    3. --validate_out=paths=source_relative,lang=go:. \
    4. xxxx.proto

    2.Add the validate command in Makefile

    1. make validate

    We can inject the validate middleware into HTTP or gRPC, and the validate middleware automatically validates the parameters according to the rules written in the proto when request entering.

    HTTP

    1. httpSrv := http.NewServer(
    2. http.Address(":8000"),
    3. http.Middleware(
    4. validate.Validator(),

    gRPC

    References