Skip to content

Commit

Permalink
Merge pull request #31 from goccy/feature/fix-encoding-for-time-type
Browse files Browse the repository at this point in the history
Fix encoding for time type
  • Loading branch information
goccy authored Nov 7, 2019
2 parents 2d04012 + 928f27c commit 220294b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
9 changes: 9 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"sort"
"strconv"
"strings"
"time"

"github.com/goccy/go-yaml/ast"
"github.com/goccy/go-yaml/internal/errors"
Expand Down Expand Up @@ -151,6 +152,9 @@ func (e *Encoder) encodeValue(v reflect.Value, column int) (ast.Node, error) {
if mapItem, ok := v.Interface().(MapItem); ok {
return e.encodeMapItem(mapItem, column)
}
if t, ok := v.Interface().(time.Time); ok {
return e.encodeTime(t, column), nil
}
}
return e.encodeStruct(v, column)
case reflect.Map:
Expand Down Expand Up @@ -342,6 +346,11 @@ func (e *Encoder) isZeroValue(v reflect.Value) bool {
return false
}

func (e *Encoder) encodeTime(v time.Time, column int) ast.Node {
value := v.Format(time.RFC3339Nano)
return ast.String(token.New(value, value, e.pos(column)))
}

func (e *Encoder) encodeStruct(value reflect.Value, column int) (ast.Node, error) {
node := ast.Mapping(token.New("", "", e.pos(column)), e.isFlowStyle)
structType := value.Type()
Expand Down
15 changes: 15 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"math"
"strconv"
"testing"
"time"

"github.com/goccy/go-yaml"
)
Expand Down Expand Up @@ -291,6 +292,20 @@ func TestEncoder(t *testing.T) {
"v: あいうえお\nv2: かきくけこ\n",
map[string]string{"v": "あいうえお", "v2": "かきくけこ"},
},

// time value
{
"v: 0001-01-01T00:00:00Z\n",
map[string]time.Time{"v": time.Time{}},
},
{
"v: 0001-01-01T00:00:00Z\n",
map[string]*time.Time{"v": &time.Time{}},
},
{
"v: null\n",
map[string]*time.Time{"v": nil},
},
}
for _, test := range tests {
var buf bytes.Buffer
Expand Down

0 comments on commit 220294b

Please sign in to comment.