Skip to content

Commit

Permalink
Merge pull request #6 from gochore/dev
Browse files Browse the repository at this point in the history
feat: support intent json
  • Loading branch information
wolfogre authored Dec 9, 2020
2 parents 30680af + 18f22ae commit b902938
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 14 deletions.
7 changes: 6 additions & 1 deletion coder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
49 changes: 36 additions & 13 deletions coder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

Expand Down

0 comments on commit b902938

Please sign in to comment.