Search code examples
jsongo

Golang JSON Date time.Date() Testing Request


I am working on Golang creating API. I have a route [PUT]: /accounts/{id}.

{
    "firstName": "MakeUPDATED",
    "lastName": "FakeUPDATED",
    "birthday": "2000-12-31 14:30:15",
    "phoneNumber": "98423423"
}

I am sending this as a request body. But in code it can not convert date to time.Time type.

type UpdateAccountRequest struct {
FirstName   string    `json:"firstName"`
LastName    string    `json:"lastName"`
Birthday    time.Time `json:"birthday"`
PhoneNumber string    `json:"phoneNumber"` }

And the test:

updateAccReq := new(models.UpdateAccountRequest)
if err = json.NewDecoder(r.Body).Decode(&updateAccReq); err != nil {
    functionalities.WriteJSON(w, http.StatusBadRequest, APIServerError{Error: "invalid request body: "+err.Error()})
    return
}

I get:

{ "error": "invalid request body: parsing time \"2000-12-31 14:30:15\" as \"2006-01-02T15:04:05Z07:00\": cannot parse \" 14:30:15\" as \"T\"" }

I would to be able to test with JSON request just on Postman. How can I solve that?


Solution

  • By default, JSON uses time.Time.UnmarshalJSON which requires RFC 3339 which is basically ISO 8601. This is <date>T<time> or 2000-12-31T14:30:15.

    You either need to change what you expect as a timestamp, or implement your own json.Unmarshaler.