gpt4 book ai didi

json - 如何为一个端点创建多种验证方法?

转载 作者:数据小太阳 更新时间:2023-10-29 03:34:03 24 4
gpt4 key购买 nike

我想制作一个验证 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 请求创建结构是否更好?还是我应该动态创建这些?如果我只有一个端点,我怎么知道发送了哪种请求?

最佳答案

如果您有一个必须接受不同 JSON 类型的端点/rpc,您需要以某种方式告诉它如何区分它们。一种选择是拥有类似的东西:

type request struct {
bodyA *requestBodyA
bodyB *requestBodyB
}

然后,将这些字段适本地填充到容器 JSON 对象中。如果存在 bodyA 键,json 模块将仅填充 bodyA,否则将其保留为 nil,依此类推上。

这是一个更完整的例子:

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()
}

另一种选择是使用 map 更动态地执行此操作,但上述方法可能就足够了。

关于json - 如何为一个端点创建多种验证方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54480198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com