diff --git a/context.go b/context.go index 90d4c6e5..7149e6ea 100644 --- a/context.go +++ b/context.go @@ -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 *******/ /************************************/ diff --git a/context_test.go b/context_test.go index 9024cfc1..6375ff41 100644 --- a/context_test.go +++ b/context_test.go @@ -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()) +}