Skip to content

util/gvalid: When customizing validation rules, passing an empty array will become a string #3636

@shuqingzai

Description

@shuqingzai

Go version

go version go1.21.10 darwin/amd64

GoFrame version

2.7.1

Can this bug be reproduced with the latest release?

Option Yes

What did you do?

参考 自定义规则-规则注册 自定义规则并使用http请求访问,使用该规则

自行编写一个 http 服务接收参数

server:
  address:     ":8199"
  openapiPath: "/api.json"
  swaggerPath: "/swagger"
package main

import (
	"context"
	"errors"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gvalid"
)


type sliceV struct{}

func init() {
	rule := sliceV{}
	gvalid.RegisterRule(rule.Name(), rule.Run)
}

func (r sliceV) Name() string {
	return "slice-v"
}

func (r sliceV) Message() string {
	return "not a slice"
}

func (r sliceV) Run(_ context.Context, in gvalid.RuleFuncInput) error {
	g.Dump(in.Value)
	for _, v := range in.Value.Slice() {
		if v == "" {
			return errors.New("empty value")
		}
	}

	if !in.Value.IsSlice() {
		return errors.New("not a slice")
	}

	return nil
}

type HelloReq 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 HelloRes struct {
	Name string   `json:"name" v:"required" dc:"Your name"`
	S    []string `json:"s" v:"slice-v" dc:"S"`
}

type Hello struct {
}

func (Hello) Say(ctx context.Context, req *HelloReq) (res *HelloRes, err error) {
	g.Log().Debugf(ctx, `receive say: %+v`, req)
	res = &HelloRes{
		Name: req.Name,
		S:    req.S,
	}
	return
}

func main() {
	s := g.Server()
	s.Use(ghttp.MiddlewareHandlerResponse)
	s.Group("/", func(group *ghttp.RouterGroup) {
		group.Bind(
			new(Hello),
		)
	})
	s.Run()
}

使用如下参数访问

curl --location --request POST 'http://127.0.0.1:8199/hello' \
--header 'Content-Type: application/json' \
--header 'Accept: */*' \
--header 'Host: 127.0.0.1:8199' \
--header 'Connection: keep-alive' \
--data-raw '{
    "name": "t",
    "s" : []
}'

What did you see happen?

错误的参数解析

image

What did you expect to see?

空 slice 的 value 不应该被视为空字符串

Metadata

Metadata

Assignees

Labels

bugIt is confirmed a bug, but don't worry, we'll handle it.doneThis issue is done, which may be release in next version.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions