如何为一个端点创建多种验证方法?
How to create multiple validation methods for one endpoint?
我想进行验证 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 类型的 endpoint/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()
}
另一种选择是使用地图更动态地执行此操作,但上述方法可能就足够了。
我想进行验证 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 类型的 endpoint/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()
}
另一种选择是使用地图更动态地执行此操作,但上述方法可能就足够了。