Skip to content

[suggestion] own Time type (would make calls to flaky API server easier) #891

@aanno

Description

@aanno

I tried oapi-codegen for client generation. Using the client, I encountered that data format the REST API server provides is not in line with https://swagger.io/docs/specification/data-models/data-types/#string (that requires RFC 3339, section 5.6).

Here are 2 samples of the flaky format: 2017-07-21T17:32:2938938 2017-07-21T17:32:3939937-07:00

Using code generated by oapi-codegen would be substantial easier if

  1. There would be an extra type for time, e.g. type Time time.Time
  2. This Time type would be used in the generated code, e.g. every occurence of *time.Time would be replaced with *Time.

With this changes in place, customising the JSON deserialisation would be possible with something like:

// https://stackoverflow.com/questions/45303326/how-to-parse-non-standard-time-format-from-json
const dtNoZ = "2006-01-02T15:04:05.999999999"
const dtNoZ2 = "2006-01-02T15:04:05.999999999-07:00"

type Time time.Time

// Implement Marshaler and Unmarshaler interface
func (j *Time) UnmarshalJSON(b []byte) error {
    s := strings.Trim(string(b), "\"")
    t, err := time.Parse(dtNoZ, s)
    if err != nil {
		t2, err := time.Parse(dtNoZ2, s)
		if err != nil {
			return err
		}
		*j = Time(t2)
		return nil
	}
    *j = Time(t)
    return nil
}
    
func (j *Time) MarshalJSON() ([]byte, error) {
    return json.Marshal(time.Time(j))
}

// Maybe a Format function for printing your date
func (j *Time) Format(s string) string {
    t := time.Time(j)
    return t.Format(s)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions