time: clean up MarshalJSON, add RFC3339 method

encoding/xml: handle time.Time as recognized type

The long term plan is to define an interface that time.Time
can implement and that encoding/xml can call, but we are
not going to try to define that interface before Go 1.
Instead, special-case time.Time in package xml, because
it is such a fundamental type, as a stop-gap.
The eventual methods will behave this way.

Fixes #2793.

R=golang-dev, r, r, n13m3y3r
CC=golang-dev
https://golang.org/cl/5634051
This commit is contained in:
Russ Cox 2012-02-07 23:37:25 -05:00
parent 3ee208533e
commit 1d8250c8b0
8 changed files with 154 additions and 82 deletions

View file

@ -12,6 +12,7 @@ import (
"reflect"
"strconv"
"strings"
"time"
)
const (
@ -223,7 +224,14 @@ func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo) error {
return nil
}
var timeType = reflect.TypeOf(time.Time{})
func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) error {
// Normally we don't see structs, but this can happen for an attribute.
if val.Type() == timeType {
p.WriteString(val.Interface().(time.Time).Format(time.RFC3339Nano))
return nil
}
switch val.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p.WriteString(strconv.FormatInt(val.Int(), 10))
@ -255,6 +263,10 @@ func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) error {
var ddBytes = []byte("--")
func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error {
if val.Type() == timeType {
p.WriteString(val.Interface().(time.Time).Format(time.RFC3339Nano))
return nil
}
s := parentStack{printer: p}
for i := range tinfo.fields {
finfo := &tinfo.fields[i]