dongshi1934 2019-05-09 11:19
浏览 104

从Django获取可为空的datetime并将其转换为golang

Here is the date that i send (in raw text) mode from a jsonified models.DateTimeField :

2019-05-07 16:49:47.351628+00:00

How i receive it in 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)
}

But when i print my object i have a :

{0001-01-01 00:00:00 +0000 UTC false}

How to convert ideally from a django time field or with string manipulation my date time to make it compatible with go and pq.NullTime ?

Everything else works (bool, int, float , string) but not the date ...

  • 写回答

1条回答 默认 最新

  • douchen2011 2019-05-09 11:30
    关注

    You need to have a custom time type in order to unmarshal custom time format:

    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
    }
    

    By default json unmarshal expects date in the RFC3339 format.

    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退