AdSense

網頁

2022/1/19

Golang unmarshal Request JSON to time.Time

Go net/http handler接收POST請求的JSON中的日期時間字串並轉為time.Time範例。


範例環境:

  • Go 1.17


範例

使用json.Decoder.Decode()http.Request.Body的JSON轉為Employee struct。Employee.CreatedAt型態為time.Time用來接收日期時間。

main.go

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

type Employee struct {
    Id        int
    Name      string
    Age       int
    CreatedAt time.Time
}

func main() {
    http.HandleFunc("/employee", func(rw http.ResponseWriter, r *http.Request) {
        switch r.Method {
        case http.MethodPost:
            var emp Employee
            if err := json.NewDecoder(r.Body).Decode(&emp); err != nil {
                panic(err)
            }
            fmt.Println(emp)
            json.NewEncoder(rw).Encode(emp)
        default:
            http.Error(rw, "Method not allowed", http.StatusMethodNotAllowed)
        }
    })

    http.ListenAndServe(":8080", nil)
}

github


Client發送請求的JSON字串如下。特別注意日期時間格式必須是RFC3339格式:

  • yyyy-MM-ddThh:mm:ssZ - e.g. 2022-01-19T18:30:15Z
  • yyyy-MM-ddThh:mm:ss±hh:mm - e.g. 2022-01-19T18:30:15+00:00
{
  "id": 1,
  "name": "john",
  "age": 33,
  "createdAt": "2022-01-19T18:30:15Z"
}

RFC3339格式日期與時間皆不可省略,兩者以大寫T隔開;後綴Z為"Zulu"的縮寫,代表UTC位移時間00:00,所以轉換的time.Time為UTC時間。

若日期和時間中間沒有加T會出現錯誤:

parsing time "\"2022-01-19 18:30:15Z\"" as "\"2006-01-02T15:04:05Z07:00\"": cannot parse " 18:30:15Z\"" as "T"


若後綴沒有加Z會出現錯誤:

parsing time "\"2022-01-19T18:30:15\"" as "\"2006-01-02T15:04:05Z07:00\"": cannot parse "\"" as "Z07:00



測試

啟動應用程式後在命令列以cURL發出以下請求。

$ curl -X POST "http://localhost:8080/employee" -H 'content-type: application/json' -d '{"id": 1, "name": "john", "age": 33, "createdAt": "2022-01-19T18:30:15Z"}'

在console印出以下。

{1 john 33 2022-01-19 18:30:15 +0000 UTC}


沒有留言:

AdSense