Add Resp response format for controller

This commit is contained in:
Maneesh Babu M 2021-04-23 02:53:53 +00:00
parent 1abbb05cef
commit d9415524aa
No known key found for this signature in database
GPG Key ID: 1C33CD6B03582880

View File

@ -21,8 +21,6 @@ import (
"encoding/xml"
"errors"
"fmt"
"github.com/gogo/protobuf/proto"
"gopkg.in/yaml.v2"
"html/template"
"io"
"mime/multipart"
@ -37,6 +35,8 @@ import (
"github.com/beego/beego/v2/server/web/context"
"github.com/beego/beego/v2/server/web/context/param"
"github.com/beego/beego/v2/server/web/session"
"github.com/gogo/protobuf/proto"
"gopkg.in/yaml.v2"
)
var (
@ -436,6 +436,22 @@ func (c *Controller) URLFor(endpoint string, values ...interface{}) string {
}
return URLFor(endpoint, values...)
}
// Resp sends response based on the Accept Header
// By default response will be in JSON
func (c *Controller) Resp(data interface{}) error {
accept := c.Ctx.Input.Header("Accept")
switch accept {
case context.ApplicationYAML:
c.Data["yaml"] = data
return c.ServeYAML()
case context.ApplicationXML, context.TextXML:
c.Data["xml"] = data
return c.ServeXML()
default:
c.Data["json"] = data
return c.ServeJSON()
}
}
// ServeJSON sends a json response with encoding charset.
func (c *Controller) ServeJSON(encoding ...bool) error {