feat(context): formating json response

This commit is contained in:
bruinxs 2018-03-04 16:16:47 +08:00
parent 5d3f30cfc8
commit e5d9c49a2d
2 changed files with 72 additions and 0 deletions

View File

@ -739,6 +739,34 @@ func (c *Context) Stream(step func(w io.Writer) bool) {
}
}
/******************************************/
/******** FORMATTING JSON RESPONSE ********/
/******************************************/
//Success response data such as {"errcode": 0, "data": data}
func (c *Context) Success(data interface{}) {
c.JSON(200, H{"errcode": 0, "data": data})
}
//Fail response fail message with json
func (c *Context) Fail(errcode int, msg string, err error, args ...interface{}) {
obj := H{"errcode": errcode, "msg": msg}
if err != nil {
obj["err"] = err.Error()
}
if len(args) > 0 {
obj["data"] = args[0]
}
c.JSON(200, obj)
c.Error(Error{Type: ErrorTypePublic, Meta: msg, Err: err})
}
//FailWithAbort fail and abort immediately
func (c *Context) FailWithAbort(errcode int, msg string, err error, args ...interface{}) {
c.Fail(errcode, msg, err, args...)
c.Abort()
}
/************************************/
/******** CONTENT NEGOTIATION *******/
/************************************/

View File

@ -1377,3 +1377,47 @@ func TestContextGetRawData(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, "Fetch binary post data", string(data))
}
func TestContextSuccess(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Success(H{"foo": "bar"})
assert.Equal(t, 200, w.Code)
assert.Equal(t, "{\"data\":{\"foo\":\"bar\"},\"errcode\":0}", w.Body.String())
assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
}
func TestContextFail(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
assert.Empty(t, c.Errors)
c.Fail(401, "not login", fmt.Errorf("auth err"), H{"foo": "bar"})
assert.Equal(t, 200, w.Code)
assert.Equal(t, "{\"data\":{\"foo\":\"bar\"},\"err\":\"auth err\",\"errcode\":401,\"msg\":\"not login\"}", w.Body.String())
assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
assert.Len(t, c.Errors, 1)
}
func TestContextFailNoErrNoArgs(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.Fail(401, "not login", nil)
assert.Equal(t, "{\"errcode\":401,\"msg\":\"not login\"}", w.Body.String())
}
func TestContextFailWithAbort(t *testing.T) {
w := httptest.NewRecorder()
c, _ := CreateTestContext(w)
c.FailWithAbort(401, "not login", fmt.Errorf("auth err"))
assert.Equal(t, 200, w.Code)
assert.Equal(t, "{\"err\":\"auth err\",\"errcode\":401,\"msg\":\"not login\"}", w.Body.String())
assert.True(t, c.IsAborted())
}