name: Response formats
sort: 8
JSON, XML and JSONP
Beego is also designed for the creation of API applications. When we build an API application, we often need to respond with JSON or XML. Beego provides a simple approach:
Respond with JSON data:
type mystruct struct {FieldOne string `json:"field_one"`}func (this *AddController) Get() {mystruct := { ... }this.Data["json"] = &mystructthis.ServeJSON()}
ServeJson will set
content-typetoapplication/jsonand JSONify the data.Respond with XML data:
func (this *AddController) Get() {mystruct := { ... }this.Data["xml"]=&mystructthis.ServeXML()}
ServeXml will set
content-typetoapplication/xmland convert the data into XML.Respond with jsonp
func (this *AddController) Get() {mystruct := { ... }this.Data["jsonp"] = &mystructthis.ServeJSONP()}
ServeJsonp will set
content-typetoapplication/javascript, JSONify the data and respond to jsonp based on the request parametercallback.
In version 1.6 names of methods were changed, it is ServeJSON(), ServeXML(), ServeJSONP() from now on.
