如何将日期字符串绑定到结构体?

huangapple go评论116阅读模式
英文:

How do I bind a date string to a struct?

问题

你好!根据你的描述,你想要将字符串数据绑定到TestModel结构体中。你可以使用time.Parse函数将字符串解析为time.Time类型,然后将其赋值给TestModel的Date字段。以下是一个简单的示例:

  1. func CreateDiary(c echo.Context) error {
  2. var getData model.TestModel
  3. dateString := c.FormValue("date") // 假设你从请求中获取到了日期字符串
  4. t, err := time.Parse("2006-01-02", dateString)
  5. if err != nil {
  6. fmt.Print(err.Error())
  7. // 处理解析错误
  8. }
  9. getData.Date = t
  10. // 其他字段的赋值...
  11. return c.JSON(200, getData)
  12. }

在这个示例中,我们使用time.Parse函数将日期字符串解析为time.Time类型,并将其赋值给TestModelDate字段。请注意,日期字符串的格式必须与解析模板"2006-01-02"匹配。

希望这个示例对你有帮助!如果你还有其他问题,请随时提问。

英文:
  1. type TestModel struct {
  2. Date time.Time `json:"date" form:"date" gorm:"index"`
  3. gorm.Model
  4. }

i'm using echo framwork, and
I have a struct like the one above, and I get string data like '2021-09-27' , how can I bind it to the struct?

  1. func CreateDiary(c echo.Context) error {
  2. var getData model.TestModel
  3. if err := (&echo.DefaultBinder{}).BindBody(c, &getData); err != nil {
  4. fmt.Print(err.Error())
  5. }
  6. return c.JSON(200, getData)
  7. }

When I code like this, I get the following error:

  1. code=400, message=parsing time "2021-09-27" as "2006-01-02T15:04:05Z07:00": cannot parse "" as "T", internal=parsing time "2021-09-27" as "2006-01-02T15:04:05Z07:00": cannot parse "" as "T"

I'm a golang beginner, can you show me a simple example??, please.

i'm using echo framwork

答案1

得分: 3

以下是echo中可用的标签列表。如果你想从请求体中解析数据,可以使用以下标签:

  • query - 数据源是请求的查询参数。
  • param - 数据源是路由路径参数。
  • header - 数据源是请求头参数。
  • form - 数据源是表单。数值从查询参数和请求体中获取。使用Go标准库进行表单解析。
  • json - 数据源是请求体。使用Go的json包进行解组。
  • xml - 数据源是请求体。使用Go的xml包进行解组。

你需要将time.Time封装到自定义结构体中,然后实现json.Marshalerjson.Unmarshaler接口。

以下是示例代码:

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "github.com/labstack/echo/v4"
  7. )
  8. type CustomTime struct {
  9. time.Time
  10. }
  11. type TestModel struct {
  12. Date CustomTime `json:"date"`
  13. }
  14. func (t CustomTime) MarshalJSON() ([]byte, error) {
  15. date := t.Time.Format("2006-01-02")
  16. date = fmt.Sprintf(`"%s"`, date)
  17. return []byte(date), nil
  18. }
  19. func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
  20. s := strings.Trim(string(b), `"`)
  21. date, err := time.Parse("2006-01-02", s)
  22. if err != nil {
  23. return err
  24. }
  25. t.Time = date
  26. return
  27. }
  28. func main() {
  29. e := echo.New()
  30. e.POST("/test", CreateDiary)
  31. e.Logger.Fatal(e.Start(":1323"))
  32. }
  33. func CreateDiary(c echo.Context) error {
  34. var getData TestModel
  35. if err := (&echo.DefaultBinder{}).BindBody(c, &getData); err != nil {
  36. fmt.Print(err.Error())
  37. }
  38. return c.JSON(200, getData)
  39. }

测试代码:

  1. curl -X POST http://localhost:1323/test -H 'Content-Type: application/json' -d '{"date":"2021-09-27"}'

请注意,以上代码是一个示例,你需要根据自己的需求进行修改和适配。

英文:

Here is list of available tags used in echo. If you want to parse from body, then use json

  • query - source is request query parameters.
  • param - source is route path parameter.
  • header - source is header parameter.
  • form - source is form. Values are taken from query and request body. Uses Go standard library form parsing.
  • json - source is request body. Uses Go json package for unmarshalling.
  • xml - source is request body. Uses Go xml package for unmarshalling.

You need to wrap time.Time into custom struct and then implement json.Marshaler and json.Unmarshaler interfaces

Example

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. "github.com/labstack/echo/v4"
  7. )
  8. type CustomTime struct {
  9. time.Time
  10. }
  11. type TestModel struct {
  12. Date CustomTime `json:"date"`
  13. }
  14. func (t CustomTime) MarshalJSON() ([]byte, error) {
  15. date := t.Time.Format("2006-01-02")
  16. date = fmt.Sprintf(`"%s"`, date)
  17. return []byte(date), nil
  18. }
  19. func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
  20. s := strings.Trim(string(b), "\"")
  21. date, err := time.Parse("2006-01-02", s)
  22. if err != nil {
  23. return err
  24. }
  25. t.Time = date
  26. return
  27. }
  28. func main() {
  29. e := echo.New()
  30. e.POST("/test", CreateDiary)
  31. e.Logger.Fatal(e.Start(":1323"))
  32. }
  33. func CreateDiary(c echo.Context) error {
  34. var getData TestModel
  35. if err := (&echo.DefaultBinder{}).BindBody(c, &getData); err != nil {
  36. fmt.Print(err.Error())
  37. }
  38. return c.JSON(200, getData)
  39. }

test

  1. curl -X POST http://localhost:1323/test -H 'Content-Type: application/json' -d '{"date":"2021-09-27"}'

答案2

得分: 3

类型 CustomTime time.Time

  1. func (ct *CustomTime) UnmarshalParam(param string) error {
  2. t, err := time.Parse(`2006-01-02`, param)
  3. if err != nil {
  4. return err
  5. }
  6. *ct = CustomTime(t)
  7. return nil
  8. }

参考:https://github.com/labstack/echo/issues/1571

英文:

Type CustomTime time.Time

  1. func (ct *CustomTime) UnmarshalParam(param string) error {
  2. t, err := time.Parse(`2006-01-02`, param)
  3. if err != nil {
  4. return err
  5. }
  6. *ct = CustomTime(t)
  7. return nil
  8. }

ref: https://github.com/labstack/echo/issues/1571

huangapple
  • 本文由 发表于 2021年9月27日 15:15:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/69342582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定