django - 从 django 获取可以为空的日期时间并将其转换为 golang
问题描述
这是我从 jsonified models.DateTimeField 发送(以原始文本)模式的日期:
2019-05-07 16:49:47.351628+00:00
我如何在 golang 中收到它:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/lib/pq"
)
type DataLink struct {
Created pq.NullTime `json:"created"`
}
type SendData struct {
Name string `json:"Name"`
}
func main() {
var reception = DataLink{}
var sendData = SendData{}
sendData.Name = "Melon"
url := "http://127.0.0.1:8309/getLinks/"
fmt.Println("URL:>", url)
js, err := json.Marshal(sendData)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(js))
req.Header.Set("X-Custom-Header", "myvalue")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
//fmt.Println("response Status:", resp.Status)
//fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
//fmt.Println("response Body:", string(body))
err = json.Unmarshal(body, &reception)
fmt.Println(reception.Created)
}
但是当我打印我的对象时,我有一个:
{0001-01-01 00:00:00 +0000 UTC false}
如何从 django 时间字段或使用字符串操作我的日期时间以使其与 go 和 pq.NullTime 兼容?
其他一切都有效(bool、int、float、string)但不是日期...
解决方案
您需要自定义时间类型才能unmarshal
自定义时间格式:
type Datetime struct {
pq.NullTime
}
func (t *Datetime) UnmarshalJSON(input []byte) error {
strInput := strings.Trim(string(input), `"`)
newTime, err := time.Parse(time.RFC3339, strInput)
if err != nil {
return err
}
t.pqNullTime = newTime
return nil
}
默认情况下,json unmarshal 需要RFC3339
格式中的日期。
推荐阅读
- python-3.x - 替换给定组数的数据框中的值
- javascript - 如何向 nock.Scope 添加扩展功能
- ansible - 无法设置环境变量以用于 ansible 角色
- r - 闪亮选择多个输入中的动态/条件过滤(selectizeInput,multiple = TRUE)
- javascript - 根据谷歌表格中单元格值的变化向特定地址发送电子邮件
- java - 带有 AWS S3 的 RESTFUL API
- javascript - 将 react 中的功能组件转换为基于类的组件
- java - 传输 ArrayList
元素到二维数组 String - .net-core-3.0 - 如何在 .net core 3.0 中阅读正文内容?
- node.js - Discord.js 语音机器人在播放本地 mp3 文件时中断