首頁  >  文章  >  後端開發  >  如何使 Protobuf 3 欄位成為必填欄位?

如何使 Protobuf 3 欄位成為必填欄位?

WBOY
WBOY轉載
2024-02-09 08:10:28655瀏覽

如何使 Protobuf 3 字段成为必填字段?

Protobuf 3 是一種高效率的資料序列化格式,但在使用過程中,有時需要將某些欄位設為必填欄位。那麼,如何讓 Protobuf 3 欄位成為必填欄位呢?在本文中,php小編草莓將為您詳細介紹如何使用 Protobuf 3 的特性來實現字段必填,並提供相應的程式碼範例。無論您是初學者或有一定經驗的開發者,本文都能幫助您快速掌握必填欄位的使用方法,提升程式碼的健全性和可靠性。讓我們一起來看看吧!

問題內容

我正在使用 grpc/proto-buffers 在 golang 中編寫我的第一個 api 端點。我對 go 還很陌生。 以下是我為測試案例編寫的文件

package my_package

import (
    "context"
    "testing"

    "github.com/stretchr/testify/require"

    "google.golang.org/protobuf/types/known/structpb"
    "github.com/myteam/myproject/cmd/eventstream/setup"
    v1handler "github.com/myteam/myproject/internal/handlers/myproject/v1"
    v1interface "github.com/myteam/myproject/proto/.gen/go/myteam/myproject/v1"
)

func testendpoint(t *testing.t) {
    conf := &setup.config{}

    // initialize our api handlers
    myhandler := v1handler.new(&v1handler.config{})

    t.run("success", func(t *testing.t) {
        res, err := myhandler.endpoint(context.background(), &v1interface.endpointrequest{
            a: "s",
            b: &structpb.struct{
                fields: map[string]*structpb.value{
                    "t": &structpb.value{
                        kind: &structpb.value_stringvalue{
                            stringvalue: "u",
                        },
                    },
                    "v": &structpb.value{
                        kind: &structpb.value_stringvalue{
                            stringvalue: "w",
                        },
                    },
                },
            },
            c: &timestamppb.timestamp{seconds: 1590179525, nanos: 0},
        })
        require.nil(t, err)

        // assert we got what we want.
        require.equal(t, "ok", res.text)
    })


}

這是在上麵包含的 v1.go 檔案中定義 endpointrequest 物件的方式:

// An v1 interface Endpoint Request object.
message EndpointRequest {

  // a is something.
  string a = 1 [(validate.rules).string.min_len = 1];

  // b can be a complex object.
  google.protobuf.Struct b = 2;

  // c is a timestamp.
  google.protobuf.Timestamp c = 3;

}

上面的測試案例似乎運作正常。

我設定了驗證規則,有效地使參數 a 成為強制參數,因為它要求 a 是一個至少包含 1 的字串。因此,如果省略 a,則端點將傳回 400。

但現在我想確保如果省略 cb 端點傳回 400。我怎樣才能做到這一點?在 protobufs 3 中,他們刪除了 required 關鍵字。那麼我如何檢查是否傳入了非字串參數並做出相應的反應?

解決方法

簡短的版本:你不能。

required 被刪除主要是因為它使變更向後不相容。嘗試使用驗證選項重新實現它並不是那麼激烈(更改更容易),但會遇到如您所見的缺點。

相反,將驗證保留在原型定義之外,並將其移至應用程式本身。每當您收到訊息時,您都應該檢查其內容(當 required 出現時也是如此)。在極少數情況下,由 options 或 required 提供的簡單驗證就足夠了。

以上是如何使 Protobuf 3 欄位成為必填欄位?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除