为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信