Title: Does the ctx.JSON() method in Gin support formatting time.Time types based on Tag definitions during JSON serialization?
Body:
Problem Description I am developing with the Gin framework and have encountered an issue regarding the ctx.JSON() method. I want to format time.Time fields based on struct field Tags during JSON serialization.
Details I have a struct defined as follows:
go
Copy code
type MyStruct struct {
ID int json:"id"
Name string json:"name"
CreatedAt time.Time json:"created_at" time:"YYYY-MM-DD"
}
In my route handler function, I use the ctx.JSON() method to return a JSON response for this struct, as shown below:
go Copy code func GetMyStruct(c *gin.Context) { myData := MyStruct{ ID: 1, Name: "Example", CreatedAt: time.Now(), } c.JSON(http.StatusOK, myData) } I would like to format the CreatedAt field's time in a specific format, such as "2006-01-02 15:04:05", in the returned JSON. However, I'm not sure if this can be achieved directly within the ctx.JSON() method of Gin or if additional handling is required.
Expected Solution I would like to know if there's a straightforward way to achieve time formatting based on Tag definitions in ctx.JSON().
Additional Information Gin Version: [Please provide the version of Gin you are using] Go Version: [Please provide the version of Go you are using] Thank you for your assistance!
Comment From: VarusHsu
It seem that it's not a issuse about gin.
Golang standrad lib json don't suppose this usage. if you marshal a type of time.Time
field in use json.Marshal. You will got RFC3339 result like 2023-09-14T12:28:29.047531+08:00
.
There is 3 ways:
1. Define youself time type and implement MarshalJson method.
2. Use timestamp instead of time type.
3. Format time at frontend.
Comment From: Meng-Xin
It seem that it's not a issuse about gin. Golang standrad lib json don't suppose this usage. if you marshal a type of
time.Time
field in use json.Marshal. You will got RFC3339 result like2023-09-14T12:28:29.047531+08:00
. There is 3 ways:
- Define youself time type and implement MarshalJson method.
- Use timestamp instead of time type.
- Format time at frontend.
First of all thank you for your solution; This is indeed not a problem with the gin framework, but I am thinking that since the framework provides the ctx.JSON() method, let this method be more powerful.