Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 007bd51

Browse files
closes gin-gonic#514, code from bobbo@b4f0b50
1 parent 72ffff6 commit 007bd51

File tree

4 files changed

+46
-0
lines changed

4 files changed

+46
-0
lines changed

context.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,11 @@ func (c *Context) XML(code int, obj interface{}) {
426426
c.Render(code, render.XML{Data: obj})
427427
}
428428

429+
// YAML serializes the given struct as YAML into the response body.
430+
func (c *Context) YAML(code int, obj interface{}) {
431+
c.Render(code, render.YAML{Data: obj})
432+
}
433+
429434
// String writes the given string into the response body.
430435
func (c *Context) String(code int, format string, values ...interface{}) {
431436
c.Status(code)

context_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,17 @@ func TestContextRenderFile(t *testing.T) {
433433
assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
434434
}
435435

436+
// TestContextRenderYAML tests that the response is serialized as YAML
437+
// and Content-Type is set to application/x-yaml
438+
func TestContextRenderYAML(t *testing.T) {
439+
c, w, _ := CreateTestContext()
440+
c.YAML(201, H{"foo": "bar"})
441+
442+
assert.Equal(t, w.Code, 201)
443+
assert.Equal(t, w.Body.String(), "foo: bar\n")
444+
assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-yaml; charset=utf-8")
445+
}
446+
436447
func TestContextHeaders(t *testing.T) {
437448
c, _, _ := CreateTestContext()
438449
c.Header("Content-Type", "text/plain")

render/render.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ var (
2020
_ Render = HTML{}
2121
_ HTMLRender = HTMLDebug{}
2222
_ HTMLRender = HTMLProduction{}
23+
_ Render = YAML{}
2324
)
2425

2526
func writeContentType(w http.ResponseWriter, value []string) {

render/yaml.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
2+
// Use of this source code is governed by a MIT style
3+
// license that can be found in the LICENSE file.
4+
5+
package render
6+
7+
import (
8+
"net/http"
9+
10+
"gopkg.in/yaml.v2"
11+
)
12+
13+
type YAML struct {
14+
Data interface{}
15+
}
16+
17+
var yamlContentType = []string{"application/x-yaml; charset=utf-8"}
18+
19+
func (r YAML) Render(w http.ResponseWriter) error {
20+
writeContentType(w, yamlContentType)
21+
22+
bytes, err := yaml.Marshal(r.Data)
23+
if err != nil {
24+
return err
25+
}
26+
27+
w.Write(bytes)
28+
return nil
29+
}

0 commit comments

Comments
 (0)