使用第三方库protoc-gen-validate,validate.proto是我从下载的库里面复制出来的,可以直接指定目录,我为了避免麻烦直接拷贝出来了

syntax = "proto3";
package services;
import "google/protobuf/timestamp.proto"; //引入timestamp的proto文件
import "validate.proto";

//商品模型
message ProdModel {
    int32 prod_id = 1;
    string prod_name = 2;
    float prod_price = 3;
}


message OrderMain {
    int32 order_id = 1; //订单id,数字
    int32 user_id = 3; //购买者id
    float order_money = 4 [(validate.rules).float.gt = 1]; //商品金额,通过(validate.rules).float.gt定义金额必须答应一
    google.protobuf.Timestamp order_time = 5; //定义时间戳字段
    repeated OrderDetail order_details = 6;
}

message OrderDetail {
    int32 detail_id = 1;
    string order_no = 2;
    int32 prod_id = 3;
    float prod_price = 4;
    int32 prod_num = 5;
}

protoc --go_out=plugins=grpc:../services --validate_out=lang=go:../services Models.proto通过这个命令重新生成Models.pb.go文件

package services

import (
    "context"
)

type OrderService struct {
}

func (this OrderService) NewOrder(c context.Context, orderRequest *OrderRequest) (*OrderResponse, error) {
    err := orderRequest.OrderMain.Validate() //在service中调用验证方法验证字段合理性
    if err != nil {
        return &OrderResponse{
            Status:  "error",
            Message: err.Error(), //验证失败返回失败语句
        }, nil
    }
    return &OrderResponse{
        Status:  "OK",
        Message: "success",
    }, nil
}

启动服务端通过postman访问接口可以看到验证不通过的error,字段小于1





12-15 09:01