diff --git a/context.go b/context.go index b043d1b..e8a9472 100644 --- a/context.go +++ b/context.go @@ -426,6 +426,11 @@ func (c *Context) XML(code int, obj interface{}) { c.Render(code, render.XML{Data: obj}) } +// YAML serializes the given struct as YAML into the response body. +func (c *Context) YAML(code int, obj interface{}) { + c.Render(code, render.YAML{Data: obj}) +} + // String writes the given string into the response body. func (c *Context) String(code int, format string, values ...interface{}) { c.Status(code) diff --git a/context_test.go b/context_test.go index 322c482..ed5c787 100644 --- a/context_test.go +++ b/context_test.go @@ -433,6 +433,17 @@ func TestContextRenderFile(t *testing.T) { assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8") } +// TestContextRenderYAML tests that the response is serialized as YAML +// and Content-Type is set to application/x-yaml +func TestContextRenderYAML(t *testing.T) { + c, w, _ := CreateTestContext() + c.YAML(201, H{"foo": "bar"}) + + assert.Equal(t, w.Code, 201) + assert.Equal(t, w.Body.String(), "foo: bar\n") + assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-yaml; charset=utf-8") +} + func TestContextHeaders(t *testing.T) { c, _, _ := CreateTestContext() c.Header("Content-Type", "text/plain") diff --git a/render/render.go b/render/render.go index 994fcd7..3808666 100644 --- a/render/render.go +++ b/render/render.go @@ -20,6 +20,7 @@ var ( _ Render = HTML{} _ HTMLRender = HTMLDebug{} _ HTMLRender = HTMLProduction{} + _ Render = YAML{} ) func writeContentType(w http.ResponseWriter, value []string) { diff --git a/render/yaml.go b/render/yaml.go new file mode 100644 index 0000000..46937d8 --- /dev/null +++ b/render/yaml.go @@ -0,0 +1,29 @@ +// Copyright 2014 Manu Martinez-Almeida. 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 ( + "net/http" + + "gopkg.in/yaml.v2" +) + +type YAML struct { + Data interface{} +} + +var yamlContentType = []string{"application/x-yaml; charset=utf-8"} + +func (r YAML) Render(w http.ResponseWriter) error { + writeContentType(w, yamlContentType) + + bytes, err := yaml.Marshal(r.Data) + if err != nil { + return err + } + + w.Write(bytes) + return nil +}