瀏覽代碼

closes #514, code from bobbo@b4f0b50

Javier Provecho 9 年之前
父節點
當前提交
007bd5124a
共有 4 個文件被更改,包括 46 次插入0 次删除
  1. 5 0
      context.go
  2. 11 0
      context_test.go
  3. 1 0
      render/render.go
  4. 29 0
      render/yaml.go

+ 5 - 0
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)

+ 11 - 0
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")

+ 1 - 0
render/render.go

@@ -20,6 +20,7 @@ var (
 	_ Render     = HTML{}
 	_ HTMLRender = HTMLDebug{}
 	_ HTMLRender = HTMLProduction{}
+	_ Render     = YAML{}
 )
 
 func writeContentType(w http.ResponseWriter, value []string) {

+ 29 - 0
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
+}