diff --git a/context.go b/context.go index 5d3b6a4e..e2b7becb 100644 --- a/context.go +++ b/context.go @@ -421,6 +421,12 @@ func (c *Context) JSON(code int, obj interface{}) { } } +// Msgpack serializes the given struct as Msgpack into the response body. +// It also sets the Content-Type as "application/msgpack" +func (c *Context) Msgpack(code int, obj interface{}) { + c.Render(code, render.Msgpack{Data: obj}) +} + // XML serializes the given struct as XML into the response body. // It also sets the Content-Type as "application/xml". func (c *Context) XML(code int, obj interface{}) { diff --git a/context_test.go b/context_test.go index 97d4957c..d1f23dec 100644 --- a/context_test.go +++ b/context_test.go @@ -444,6 +444,17 @@ func TestContextRenderYAML(t *testing.T) { assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-yaml; charset=utf-8") } +// TestContextRenderMsgpack tests that the response is serialized as Msgpack +// and Content-Type is set to application/x-msgpack +func TestContextRenderMsgpack(t *testing.T) { + c, w, _ := CreateTestContext() + c.Msgpack(201, H{"foo": "bar"}) + + assert.Equal(t, w.Code, 201) + assert.Equal(t, w.Body.Bytes(), []byte{129, 163, 102, 111, 111, 163, 98, 97, 114}) + assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-msgpack; charset=utf-8") +} + func TestContextHeaders(t *testing.T) { c, _, _ := CreateTestContext() c.Header("Content-Type", "text/plain") diff --git a/render/msgpack.go b/render/msgpack.go new file mode 100644 index 00000000..0298106b --- /dev/null +++ b/render/msgpack.go @@ -0,0 +1,22 @@ +// Copyright 2016 Andida Syahendar. All rights reserved. +// Use of this source code is governed by a MIT style +// license that can be found in the LICENSE file. + +package render + +import ( + "gopkg.in/vmihailenco/msgpack.v2" + "net/http" +) + +type Msgpack struct { + Data interface{} +} + +var msgpackContentType = []string{"application/x-msgpack; charset=utf-8"} + +func (r Msgpack) Render(w http.ResponseWriter) error { + writeContentType(w, msgpackContentType) + + return msgpack.NewEncoder(w).Encode(r.Data) +} diff --git a/render/render_test.go b/render/render_test.go index 7a6ffb7d..44375a94 100644 --- a/render/render_test.go +++ b/render/render_test.go @@ -82,6 +82,19 @@ func TestRenderXML(t *testing.T) { assert.Equal(t, w.Header().Get("Content-Type"), "application/xml; charset=utf-8") } +func TestRenderMsgpack(t *testing.T) { + w := httptest.NewRecorder() + data := map[string]interface{}{ + "foo": "bar", + } + + err := (Msgpack{data}).Render(w) + + assert.NoError(t, err) + assert.Equal(t, w.Body.Bytes(), []byte{129, 163, 102, 111, 111, 163, 98, 97, 114}) + assert.Equal(t, w.Header().Get("Content-Type"), "application/x-msgpack; charset=utf-8") +} + func TestRenderRedirect(t *testing.T) { // TODO }