'Golang echo.JSON turns Zero time.Time as Empty String but I Expect to be Returned as "0001-01-01 00:00:00"
Hi I want to ask some question regarding Golang echo.JSON() method. This line of code will return a virtualAccount struct
func (h virtualAccountsServiceHandler) Get(c echo.Context) (err error) {
virtualAccountID := c.Param("id")
virtualAccount, err := h.service.GetByID(c.Request().Context(), virtualAccountID)
if err != nil {
return
}
return c.JSON(http.StatusOK, virtualAccount)}
And this is the struct
type VirtualAccount struct {
ID string `json:"id"`
ExpirationDate time.Time `json:"expirationDate"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt time.Time `json:"-"`}
This function returns normally if the ExpirationDate is a normal date. But the problem arise when the data contains zero time.Time (0001-01-01 00:00:00.000 as stated here https://pkg.go.dev/time).
h.service.GetByID method will returns the date as it is (0001-01-01 00:00:00.000) but the echo.JSON will return empty string "" because now the time data has value of time.Time{}.
How to make echo.JSON returns it as it is (0001-01-01 00:00:00.000)?
Solution 1:[1]
I tested this code:
package main
import (
"net/http"
"time"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
type Account struct {
ExpirationDate time.Time `json:"expirationDate"`
}
func hello(c echo.Context) error {
acc := Account{}
return c.JSON(http.StatusOK, acc)
}
func main() {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.GET("/", hello)
e.Logger.Fatal(e.Start(":1323"))
}
Its execution went like this:
$ go run main.go
____ __
/ __/___/ / ___
/ _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.7.2
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
O\
? http server started on [::]:1323
{"time":"2022-04-30T17:06:24.090332232-03:00","id":"","remote_ip":"127.0.0.1","host":"localhost:1323","method":"GET","uri":"/","user_agent":"curl/7.29.0","status":200,"error":"","latency":146878,"latency_human":"146.878µs","bytes_in":0,"bytes_out":42}
However it returned what you expected:
$ curl localhost:1323
{"expirationDate":"0001-01-01T00:00:00Z"}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Everton |
