Skip to content

Commit

Permalink
closes gin-gonic#514, code from bobbo@b4f0b50
Browse files Browse the repository at this point in the history
  • Loading branch information
javierprovecho committed Apr 14, 2016
1 parent 72ffff6 commit 007bd51
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
5 changes: 5 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
11 changes: 11 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
1 change: 1 addition & 0 deletions render/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ var (
_ Render = HTML{}
_ HTMLRender = HTMLDebug{}
_ HTMLRender = HTMLProduction{}
_ Render = YAML{}
)

func writeContentType(w http.ResponseWriter, value []string) {
Expand Down
29 changes: 29 additions & 0 deletions render/yaml.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 007bd51

Please sign in to comment.