1. 程式人生 > >beego——多種格式的資料輸出

beego——多種格式的資料輸出

beego當初設計的時候就考慮了API功能的設計,而我們在設計API的時候經常是輸出JSON或者XML資料,那麼beego提供了這樣的方式直接輸出:

 

1.JSON格式輸出

func (this *AddController) Get() {
    mystruct := { ... }
    this.Data["json"] = &mystruct
    this.ServeJSON()
}

呼叫ServerJSON之後,會設定content-type 為 application/json,然後同時把資料進行 JSON 序列化輸出。

 

2.XML格式輸出

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

呼叫 ServeXML 之後,會設定 content-type 為 application/xml,同時資料會進行 XML 序列化輸出。

 

3.jsonp呼叫

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

呼叫 ServeJSONP 之後,會設定 content-type 為 application/javascript,然後同時把資料進行 JSON 序列化,然後根據請求的 callback 引數設定 jsonp 輸出。

 

開發模式下序列化後輸出的是格式化易閱讀的 JSON 或 XML 字串;在生產模式下序列化後輸出的是壓縮的字串。