skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    As a problem was a time.Time type, I used time.Parse() with layout. So it converted my "panicky" string to time.Time. Here you go:

    var birthday time.Time
        if createAccReq.Birthday != "" {
            var parseErr error
            birthday, parseErr = time.Parse("2006-01-02", createAccReq.Birthday)
            if parseErr != nil {
                return
            }
        }
    
    // time.Parse(LAYOUT, DECODED_VAL)
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search