Skip to content

Commit da84fd7

Browse files
jmcnevinMarcin Romaszewicz
authored andcommitted
Added custom types for un/marshaling (#92)
* Added custom types for marshaling This adds special handling for "date" and "byte" string formats in OpenAPI 3. When marshaled, "date" strings should have their time truncated, and "byte" strings should be Base64 encoded. * Remove unnecessary byte handling * Use struct to track import mappings
0 parents  commit da84fd7

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

date.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package types
2+
3+
import (
4+
"encoding/json"
5+
"time"
6+
)
7+
8+
const dateFormat = "2006-01-02"
9+
10+
type Date struct {
11+
time.Time
12+
}
13+
14+
func (d Date) MarshalJSON() ([]byte, error) {
15+
return json.Marshal(d.Time.Format(dateFormat))
16+
}
17+
18+
func (d *Date) UnmarshalJSON(data []byte) error {
19+
var dateStr string
20+
err := json.Unmarshal(data, &dateStr)
21+
if err != nil {
22+
return err
23+
}
24+
parsed, err := time.Parse(dateFormat, dateStr)
25+
if err != nil {
26+
return err
27+
}
28+
d.Time = parsed
29+
return nil
30+
}

date_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package types
2+
3+
import (
4+
"encoding/json"
5+
"testing"
6+
"time"
7+
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func TestDate_MarshalJSON(t *testing.T) {
12+
testDate := time.Date(2019, 4, 1, 0, 0, 0, 0, time.UTC)
13+
b := struct {
14+
DateField Date `json:"date"`
15+
}{
16+
DateField: Date{testDate},
17+
}
18+
jsonBytes, err := json.Marshal(b)
19+
assert.NoError(t, err)
20+
assert.JSONEq(t, `{"date":"2019-04-01"}`, string(jsonBytes))
21+
}
22+
23+
func TestDate_UnmarshalJSON(t *testing.T) {
24+
testDate := time.Date(2019, 4, 1, 0, 0, 0, 0, time.UTC)
25+
jsonStr := `{"date":"2019-04-01"}`
26+
b := struct {
27+
DateField Date `json:"date"`
28+
}{}
29+
err := json.Unmarshal([]byte(jsonStr), &b)
30+
assert.NoError(t, err)
31+
assert.Equal(t, testDate, b.DateField.Time)
32+
}

0 commit comments

Comments
 (0)