英文:
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
类型,并将其赋值给TestModel
的Date
字段。请注意,日期字符串的格式必须与解析模板"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.Marshaler
和json.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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论