使用第三方庫進行字段驗證


使用第三方庫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






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM