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

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


蝴蝶不菲
浏览 95回答 1
1回答

www说

如果您有一个必须接受不同 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()}另一种选择是使用地图更动态地执行此操作,但上面的方法可能就足够了。
打开App,查看更多内容
随时随地看视频慕课网APP