gin icon indicating copy to clipboard operation
gin copied to clipboard

custom time.Time type can not use ShoudBindQuery get a value ,error : invalid character '-' after top-level value

Open dreamlu opened this issue 1 year ago • 4 comments

Description

const Layout     = "2006-01-02 15:04:05"     // datetime
// CTime china time/date
// format Layout
type CTime time.Time

func (t CTime) MarshalJSON() ([]byte, error) {
	return marshalJSON[CTime](t)
}

func (t *CTime) UnmarshalJSON(b []byte) error {
	s := strings.Trim(string(b), `"`)
	if s == "" {
		return nil
	}
	if len(s) <= 10 {
		s = fmt.Sprintf("%s 00:00:00", s)
	}
	ti, err := parse(Layout, s)
	if err != nil {
		return err
	}
	*t = CTime(ti)
	return nil
}
func parse(layout, value string) (t time.Time, err error) {
	t, err = time.ParseInLocation(layout, value, time.Local)
	if err != nil {
		value = fmt.Sprintf(`"%s"`, value)
		err = t.UnmarshalJSON([]byte(value))
		return
	}
	return
}

model

type TOccupyAsset struct {
	global.GVA_MODEL_V2
	T             time.CTime     `json:"t" form:"t" gorm:"column:t;" swaggertype:"string"`
}

query

func FindTOccupyAsset(c *gin.Context) {
	var tOccupyAsset TOccupyAsset
	err := c.ShouldBindQuery(&tOccupyAsset)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	// ....
}

Actual result

// http://127.0.0.1:8888/tOccupyAsset/findTOccupyAsset?t=2024-08-09 10:10:10

error message: invalid character '-' after top-level value

this problem occur to the source code: bind query.go and the method func mapForm()

in this function about custom time type error handle image image

this is not ptr

maybe like gorm handle custom type?

Environment

  • go version: v1.22.5
  • gin version (or commit ref): v1.9.0
  • operating system: win11

dreamlu avatar Aug 20 '24 02:08 dreamlu

issue like 3919 get request shoudbuildquey has this problem

dreamlu avatar Aug 20 '24 02:08 dreamlu

image

JimChenWYU avatar Aug 20 '24 15:08 JimChenWYU

@JimChenWYU url not shoud add "", this error happened before func (t *CTime) UnmarshalJSON(b []byte) error {xxx}

dreamlu avatar Sep 03 '24 07:09 dreamlu

问题类似3919 获取请求 shoudbuildquey有这个问题

该pr已安全解决上述问题 #3933

Madou-Shinni avatar Oct 11 '24 06:10 Madou-Shinni