将标题重写如下:如何在Golang的echo.JSON中将时间变为零,并返回为“0001-01-01 00:00:00”,而不是空字符串?
时间:2024-02-11
浏览:456
作者:佚名
小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《将标题重写如下:如何在Golang的echo.JSON中将时间变为零,并返回为“0001-01-01 00:00:00”,而不是空字符串?》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!
问题内容
您好,我想问一些有关 golang echo.json() 方法的问题。这行代码将返回一个 virtualaccount 结构体
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)}
这就是结构
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:"-"`}
如果 expirationdate 是正常日期,则此函数正常返回。但是,当数据包含零 time.time (0001-01-01 00:00:00.000,如此处所述 https://pkg.go.dev/time)时,就会出现问题。
h.service.getbyid 方法将按原样返回日期 (0001-01-01 00:00:00.000),但 echo.json 将返回空字符串 "" 因为现在时间数据的值为time.时间{}。
如何使 echo.json 按原样返回它(0001-01-01 00:00:00.000)?
正确答案
我测试了这段代码:
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"))
}
它的执行过程是这样的:
$ 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}
但是它返回了您所期望的结果:
$ curl localhost:1323
{"expirationDate":"0001-01-01T00:00:00Z"}到这里,我们也就讲完了《将标题重写如下:如何在Golang的echo.JSON中将时间变为零,并返回为“0001-01-01 00:00:00”,而不是空字符串?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
12.01
热门专题
