-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Allow for custom JSON encoding implementations (#1880)
* Allow for custom JSON encoding implementations Co-authored-by: toimtoimtoim <[email protected]>
- Loading branch information
Showing
5 changed files
with
151 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package echo | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"net/http" | ||
) | ||
|
||
// DefaultJSONSerializer implements JSON encoding using encoding/json. | ||
type DefaultJSONSerializer struct{} | ||
|
||
// Serialize converts an interface into a json and writes it to the response. | ||
// You can optionally use the indent parameter to produce pretty JSONs. | ||
func (d DefaultJSONSerializer) Serialize(c Context, i interface{}, indent string) error { | ||
enc := json.NewEncoder(c.Response()) | ||
if indent != "" { | ||
enc.SetIndent("", indent) | ||
} | ||
return enc.Encode(i) | ||
} | ||
|
||
// Deserialize reads a JSON from a request body and converts it into an interface. | ||
func (d DefaultJSONSerializer) Deserialize(c Context, i interface{}) error { | ||
err := json.NewDecoder(c.Request().Body).Decode(i) | ||
if ute, ok := err.(*json.UnmarshalTypeError); ok { | ||
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Unmarshal type error: expected=%v, got=%v, field=%v, offset=%v", ute.Type, ute.Value, ute.Field, ute.Offset)).SetInternal(err) | ||
} else if se, ok := err.(*json.SyntaxError); ok { | ||
return NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Syntax error: offset=%v, error=%v", se.Offset, se.Error())).SetInternal(err) | ||
} | ||
return err | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
package echo | ||
|
||
import ( | ||
testify "github.com/stretchr/testify/assert" | ||
"net/http" | ||
"net/http/httptest" | ||
"strings" | ||
"testing" | ||
) | ||
|
||
// Note this test is deliberately simple as there's not a lot to test. | ||
// Just need to ensure it writes JSONs. The heavy work is done by the context methods. | ||
func TestDefaultJSONCodec_Encode(t *testing.T) { | ||
e := New() | ||
req := httptest.NewRequest(http.MethodPost, "/", nil) | ||
rec := httptest.NewRecorder() | ||
c := e.NewContext(req, rec).(*context) | ||
|
||
assert := testify.New(t) | ||
|
||
// Echo | ||
assert.Equal(e, c.Echo()) | ||
|
||
// Request | ||
assert.NotNil(c.Request()) | ||
|
||
// Response | ||
assert.NotNil(c.Response()) | ||
|
||
//-------- | ||
// Default JSON encoder | ||
//-------- | ||
|
||
enc := new(DefaultJSONSerializer) | ||
|
||
err := enc.Serialize(c, user{1, "Jon Snow"}, "") | ||
if assert.NoError(err) { | ||
assert.Equal(userJSON+"\n", rec.Body.String()) | ||
} | ||
|
||
req = httptest.NewRequest(http.MethodPost, "/", nil) | ||
rec = httptest.NewRecorder() | ||
c = e.NewContext(req, rec).(*context) | ||
err = enc.Serialize(c, user{1, "Jon Snow"}, " ") | ||
if assert.NoError(err) { | ||
assert.Equal(userJSONPretty+"\n", rec.Body.String()) | ||
} | ||
} | ||
|
||
// Note this test is deliberately simple as there's not a lot to test. | ||
// Just need to ensure it writes JSONs. The heavy work is done by the context methods. | ||
func TestDefaultJSONCodec_Decode(t *testing.T) { | ||
e := New() | ||
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(userJSON)) | ||
rec := httptest.NewRecorder() | ||
c := e.NewContext(req, rec).(*context) | ||
|
||
assert := testify.New(t) | ||
|
||
// Echo | ||
assert.Equal(e, c.Echo()) | ||
|
||
// Request | ||
assert.NotNil(c.Request()) | ||
|
||
// Response | ||
assert.NotNil(c.Response()) | ||
|
||
//-------- | ||
// Default JSON encoder | ||
//-------- | ||
|
||
enc := new(DefaultJSONSerializer) | ||
|
||
var u = user{} | ||
err := enc.Deserialize(c, &u) | ||
if assert.NoError(err) { | ||
assert.Equal(u, user{ID: 1, Name: "Jon Snow"}) | ||
} | ||
|
||
var userUnmarshalSyntaxError = user{} | ||
req = httptest.NewRequest(http.MethodPost, "/", strings.NewReader(invalidContent)) | ||
rec = httptest.NewRecorder() | ||
c = e.NewContext(req, rec).(*context) | ||
err = enc.Deserialize(c, &userUnmarshalSyntaxError) | ||
assert.IsType(&HTTPError{}, err) | ||
assert.EqualError(err, "code=400, message=Syntax error: offset=1, error=invalid character 'i' looking for beginning of value, internal=invalid character 'i' looking for beginning of value") | ||
|
||
var userUnmarshalTypeError = struct { | ||
ID string `json:"id"` | ||
Name string `json:"name"` | ||
}{} | ||
|
||
req = httptest.NewRequest(http.MethodPost, "/", strings.NewReader(userJSON)) | ||
rec = httptest.NewRecorder() | ||
c = e.NewContext(req, rec).(*context) | ||
err = enc.Deserialize(c, &userUnmarshalTypeError) | ||
assert.IsType(&HTTPError{}, err) | ||
assert.EqualError(err, "code=400, message=Unmarshal type error: expected=string, got=number, field=id, offset=7, internal=json: cannot unmarshal number into Go struct field .id of type string") | ||
|
||
} |