亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何為一個端點創建多種驗證方法?

如何為一個端點創建多種驗證方法?

Go
蝴蝶不菲 2023-06-05 16:59:33
我想制作一個驗證 api 以驗證一組關于特定規則集的 json 請求。為此,我只想使用一個端點并調用與特定 json 結構相對應的函數。我知道 go 中沒有方法重載,所以我有點難過。...type requestBodyA struct {    SomeField   string `json:"someField"`    SomeOtherField  string `json:"someOtherField"`}type requestBodyB struct {    SomeDifferentField   string `json:"someDifferentField"`    SomeOtherDifferentField  string `json:"someOtherDifferentField"`}type ValidationService interface {    ValidateRequest(ctx context.Context, s string) (err error)}type basicValidationService struct{}...因此,為了驗證大量不同的 json 請求,為每個 json 請求創建結構是否更好?還是我應該動態創建這些?如果我只有一個端點,我怎么知道發送了哪種請求?
查看完整描述

1 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

如果您有一個必須接受不同 JSON 類型的端點/rpc,您需要以某種方式告訴它如何區分它們。一種選擇是有類似的東西:


type request struct {

  bodyA *requestBodyA

  bodyB *requestBodyB

}

然后,將這些字段適當地填充到容器 JSON 對象中。該模塊將僅在存在鍵時json填充,否則將其保留為,依此類推。bodyAbodyAnil


這是一個更完整的例子:


type RequestBodyFoo struct {

    Name    string

    Balance float64

}


type RequestBodyBar struct {

    Id  int

    Ref int

}


type Request struct {

    Foo *RequestBodyFoo

    Bar *RequestBodyBar

}


func (r *Request) Show() {

    if r.Foo != nil {

        fmt.Println("Request has Foo:", *r.Foo)

    }

    if r.Bar != nil {

        fmt.Println("Request has Bar:", *r.Bar)

    }

}


func main() {

    bb := []byte(`

    {

        "Foo": {"Name": "joe", "balance": 4591.25}

    }

    `)


    var req Request

    if err := json.Unmarshal(bb, &req); err != nil {

        panic(err)

    }

    req.Show()


    var req2 Request

    bb = []byte(`

    {

        "Bar": {"Id": 128992, "Ref": 801472}

    }

    `)

    if err := json.Unmarshal(bb, &req2); err != nil {

        panic(err)

    }

    req2.Show()

}

另一種選擇是使用地圖更動態地執行此操作,但上面的方法可能就足夠了。


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號