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:

    1. type mystruct struct {
    2. FieldOne string `json:"field_one"`
    3. }
    4. func (this *AddController) Get() {
    5. mystruct := { ... }
    6. this.Data["json"] = &mystruct
    7. this.ServeJSON()
    8. }

    ServeJson will set content-type to application/json and JSONify the data.

  • Respond with XML data:

    1. func (this *AddController) Get() {
    2. mystruct := { ... }
    3. this.Data["xml"]=&mystruct
    4. this.ServeXML()
    5. }

    ServeXml will set content-type to application/xml and convert the data into XML.

  • Respond with jsonp

    1. func (this *AddController) Get() {
    2. mystruct := { ... }
    3. this.Data["jsonp"] = &mystruct
    4. this.ServeJSONP()
    5. }

    ServeJsonp will set content-type to application/javascript , JSONify the data and respond to jsonp based on the request parameter callback.

In version 1.6 names of methods were changed, it is ServeJSON(), ServeXML(), ServeJSONP() from now on.