Skip to content

Commit 200b373

Browse files
committed
Add package: jsonhelper
1 parent 29761c4 commit 200b373

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
Package jsonhelper is a collection of convenient functions for manipulating JSON.
3+
*/
4+
package jsonhelper
5+
6+
import (
7+
"bytes"
8+
"encoding/json"
9+
"io"
10+
)
11+
12+
// ToJSON converts v to JSON.
13+
func ToJSON(v interface{}) (string, error) {
14+
var buf bytes.Buffer
15+
encoder := newEncoderFunc(&buf)
16+
if err := encoder.Encode(v); err != nil {
17+
return "", err
18+
}
19+
return buf.String(), nil
20+
}
21+
22+
// for testing
23+
type encoder interface {
24+
Encode(v interface{}) error
25+
}
26+
27+
// for testing
28+
var newEncoderFunc = func(w io.Writer) encoder {
29+
return json.NewEncoder(w)
30+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package jsonhelper
2+
3+
import (
4+
"errors"
5+
"io"
6+
"testing"
7+
)
8+
9+
func TestJsonhelper_ToJSON(t *testing.T) {
10+
foo := struct {
11+
Bar string `json:"bar"`
12+
Baz int `json:"baz"`
13+
}{
14+
Bar: "barbar",
15+
Baz: 1,
16+
}
17+
18+
actual, err := ToJSON(foo)
19+
if err != nil {
20+
t.Fatalf("err %s", err)
21+
}
22+
expected := "{\"bar\":\"barbar\",\"baz\":1}\n"
23+
if actual != expected {
24+
t.Errorf(`unexpected : expected: "%s" actual: "%s"`, expected, actual)
25+
}
26+
}
27+
28+
func TestJsonhelper_ToJSON_Error(t *testing.T) {
29+
expected := errInMock
30+
31+
newEncoderFunc = func(w io.Writer) encoder { return &mockEncoder{} }
32+
33+
_, actual := ToJSON(struct{}{})
34+
if actual != expected {
35+
t.Errorf(`unexpected : expected: "%s" actual: "%s"`, expected, actual)
36+
}
37+
}
38+
39+
var errInMock = errors.New("error in mock")
40+
41+
type mockEncoder struct{}
42+
43+
func (m *mockEncoder) Encode(v interface{}) error { return errInMock }

0 commit comments

Comments
 (0)