Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

binding time.Time with empty value returns error #4098

Closed
lifeforfun opened this issue Nov 19, 2024 · 0 comments · May be fixed by #4105 or #4103
Closed

binding time.Time with empty value returns error #4098

lifeforfun opened this issue Nov 19, 2024 · 0 comments · May be fixed by #4105 or #4103

Comments

@lifeforfun
Copy link

  • With issues:
    • Use the search tool before opening a new issue.
    • Please provide source code and commit sha if you found a bug.
    • Review existing issues and provide feedback or react to them.

Description

Binding query parameter to time.Time field,when query parameter is a zero value, ShouldBind returns error.

How to reproduce

package main

import (
	"github.com/gin-gonic/gin"
)

func main() {
	g := gin.Default()
	g.GET("/", func(c *gin.Context) {
		var req struct {
			CreatedAt time.Time `form:"created_at" time_format:"unix"`
		}
		if err := c.ShouldBind(&req); err != nil {
			str := fmt.Sprintf("\n======err:%v\n", err)
			c.String(200, str)
			return
		}
		c.String(200, req.CreatedAt.String())
	})
	g.Run(":9000")
}

Expectations

$ curl "http://localhost:9000/?created_at="
1970-01-01 08:00:00 +0800 CST

Actual result

$ curl "http://localhost:9000/?created_at="
======err:strconv.ParseInt: parsing "": invalid syntax
0001-01-01 00:00:00 +0000 UTC

Environment

  • go version: go version go1.23.0 darwin/arm64
  • gin version (or commit ref): 1.9.1
  • operating system: mac m2

I think these lines of code should move up to function start

gin/binding/form_mapping.go

Lines 417 to 420 in e46bd52

if val == "" {
value.Set(reflect.ValueOf(time.Time{}))
return nil
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
1 participant