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

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

How do I bind a date string to a struct?

问题

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

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

    return c.JSON(200, getData)
}

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

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

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

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?

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

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

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接口。

以下是示例代码:

package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/labstack/echo/v4"
)

type CustomTime struct {
	time.Time
}

type TestModel struct {
	Date CustomTime `json:"date"`
}

func (t CustomTime) MarshalJSON() ([]byte, error) {
	date := t.Time.Format("2006-01-02")
	date = fmt.Sprintf(`"%s"`, date)
	return []byte(date), nil
}

func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
	s := strings.Trim(string(b), `"`)

	date, err := time.Parse("2006-01-02", s)
	if err != nil {
		return err
	}
	t.Time = date
	return
}

func main() {
	e := echo.New()
	e.POST("/test", CreateDiary)
	e.Logger.Fatal(e.Start(":1323"))
}

func CreateDiary(c echo.Context) error {
	var getData TestModel
	if err := (&echo.DefaultBinder{}).BindBody(c, &getData); err != nil {
		fmt.Print(err.Error())
	}
	return c.JSON(200, getData)
}

测试代码:

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

package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/labstack/echo/v4"
)

type CustomTime struct {
	time.Time
}

type TestModel struct {
	Date CustomTime `json:"date"`
}

func (t CustomTime) MarshalJSON() ([]byte, error) {
	date := t.Time.Format("2006-01-02")
	date = fmt.Sprintf(`"%s"`, date)
	return []byte(date), nil
}

func (t *CustomTime) UnmarshalJSON(b []byte) (err error) {
	s := strings.Trim(string(b), "\"")

	date, err := time.Parse("2006-01-02", s)
	if err != nil {
		return err
	}
	t.Time = date
	return
}

func main() {
	e := echo.New()
	e.POST("/test", CreateDiary)
	e.Logger.Fatal(e.Start(":1323"))
}

func CreateDiary(c echo.Context) error {
	var getData TestModel
	if err := (&echo.DefaultBinder{}).BindBody(c, &getData); err != nil {
		fmt.Print(err.Error())
	}
	return c.JSON(200, getData)
}

test

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

答案2

得分: 3

类型 CustomTime time.Time

func (ct *CustomTime) UnmarshalParam(param string) error {
	t, err := time.Parse(`2006-01-02`, param)
	if err != nil {
		return err
	}
	*ct = CustomTime(t)
	return nil
}

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

英文:

Type CustomTime time.Time

func (ct *CustomTime) UnmarshalParam(param string) error {
	t, err := time.Parse(`2006-01-02`, param)
	if err != nil {
		return err
	}
	*ct = CustomTime(t)
	return nil
}

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:

确定