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.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度