diff --git a/coder.go b/coder.go index 9bfb940..bc84df6 100644 --- a/coder.go +++ b/coder.go @@ -27,10 +27,15 @@ func (c GobCoder) Decode(reader io.Reader, v interface{}) error { // JsonCoder implements Coder with json type JsonCoder struct { + Intent bool } func (c JsonCoder) Encode(writer io.Writer, v interface{}) error { - return json.NewEncoder(writer).Encode(v) + enc := json.NewEncoder(writer) + if c.Intent { + enc.SetIndent("", "\t") + } + return enc.Encode(v) } func (c JsonCoder) Decode(reader io.Reader, v interface{}) error { diff --git a/coder_test.go b/coder_test.go index 5d8b436..767be27 100644 --- a/coder_test.go +++ b/coder_test.go @@ -33,28 +33,51 @@ func TestGobCoder(t *testing.T) { } func TestJsonCoder(t *testing.T) { - c := JsonCoder{} - want := &Person{ Id: "jason", Name: "Jason Song", Age: 25, } - buffer := bytes.NewBuffer(nil) - if err := c.Encode(buffer, want); err != nil { - t.Fatal(err) - } + { + c := JsonCoder{} - t.Logf("%q", buffer.String()) + buffer := bytes.NewBuffer(nil) + if err := c.Encode(buffer, want); err != nil { + t.Fatal(err) + } - got := &Person{} - if err := c.Decode(buffer, got); err != nil { - t.Fatal(err) - } + t.Logf("%q", buffer.String()) - if !reflect.DeepEqual(got, want) { - t.Errorf("got %+v, want %+v", got, want) + got := &Person{} + if err := c.Decode(buffer, got); err != nil { + t.Fatal(err) + } + + if !reflect.DeepEqual(got, want) { + t.Errorf("got %+v, want %+v", got, want) + } + } + { + c := JsonCoder{ + Intent: true, + } + + buffer := bytes.NewBuffer(nil) + if err := c.Encode(buffer, want); err != nil { + t.Fatal(err) + } + + t.Logf("%q", buffer.String()) + + got := &Person{} + if err := c.Decode(buffer, got); err != nil { + t.Fatal(err) + } + + if !reflect.DeepEqual(got, want) { + t.Errorf("got %+v, want %+v", got, want) + } } }