1
0
mirror of https://github.com/gogf/gf.git synced 2025-04-05 03:05:05 +08:00

fix(util/gvalid): retrive empty slice parameter in custom validation rule function failed (#3795)

This commit is contained in:
John Guo 2024-09-23 19:59:48 +08:00 committed by GitHub
parent 8a1c97f518
commit e15b543a5b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 84 additions and 2 deletions

View File

@ -296,12 +296,14 @@ func (v *Validator) doCheckStruct(ctx context.Context, object interface{}) Error
if value != nil {
switch checkRuleItem.FieldKind {
case reflect.Struct, reflect.Map:
// empty struct or map.
if gconv.String(value) == emptyJsonObjectStr {
value = ""
value = nil
}
case reflect.Slice, reflect.Array:
// empty slice.
if gconv.String(value) == emptyJsonArrayStr {
value = ""
value = []any{}
}
default:
}

View File

@ -8,8 +8,15 @@ package gvalid_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/util/guid"
"github.com/gogf/gf/v2/util/gvalid"
)
@ -34,3 +41,76 @@ func Test_Issue2503(t *testing.T) {
t.Fatal(err)
}
}
type Issue3636SliceV struct{}
func init() {
rule := Issue3636SliceV{}
gvalid.RegisterRule(rule.Name(), rule.Run)
}
func (r Issue3636SliceV) Name() string {
return "slice-v"
}
func (r Issue3636SliceV) Message() string {
return "not a slice"
}
func (r Issue3636SliceV) Run(_ context.Context, in gvalid.RuleFuncInput) error {
for _, v := range in.Value.Slice() {
if v == "" {
return gerror.New("empty value")
}
}
if !in.Value.IsSlice() {
return gerror.New("not a slice")
}
return nil
}
type Issue3636HelloReq struct {
g.Meta `path:"/hello" method:"POST"`
Name string `json:"name" v:"required" dc:"Your name"`
S []string `json:"s" v:"slice-v" dc:"S"`
}
type Issue3636HelloRes struct {
Name string `json:"name" v:"required" dc:"Your name"`
S []string `json:"s" v:"slice-v" dc:"S"`
}
type Issue3636Hello struct{}
func (Issue3636Hello) Say(ctx context.Context, req *Issue3636HelloReq) (res *Issue3636HelloRes, err error) {
res = &Issue3636HelloRes{
Name: req.Name,
S: req.S,
}
return
}
// https://github.com/gogf/gf/issues/3636
func Test_Issue3636(t *testing.T) {
s := g.Server(guid.S())
s.Use(ghttp.MiddlewareHandlerResponse)
s.Group("/", func(group *ghttp.RouterGroup) {
group.Bind(
new(Issue3636Hello),
)
})
s.SetDumpRouterMap(false)
s.Start()
defer s.Shutdown()
time.Sleep(100 * time.Millisecond)
gtest.C(t, func(t *gtest.T) {
c := g.Client()
c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort()))
t.Assert(
c.PostContent(ctx, "/hello", `{"name": "t", "s" : []}`),
`{"code":0,"message":"","data":{"name":"t","s":[]}}`,
)
})
}