beego多種格式數(shù)據(jù)輸出

2023-11-20 18:06 更新

JSON、XML、JSONP

beego 當(dāng)初設(shè)計(jì)的時(shí)候就考慮了 API 功能的設(shè)計(jì),而我們?cè)谠O(shè)計(jì) API 的時(shí)候經(jīng)常是輸出 JSON 或者 XML 數(shù)據(jù),那么 beego 提供了這樣的方式直接輸出:

注意 struct 屬性應(yīng)該 為 exported Identifier 首字母應(yīng)該大寫

  • JSON 數(shù)據(jù)直接輸出:
      func (this *AddController) Get() {
          mystruct := { ... }
          this.Data["json"] = &mystruct
          this.ServeJSON()
      }
    
    調(diào)用 ServeJSON 之后,會(huì)設(shè)置 content-type 為 application/json,然后同時(shí)把數(shù)據(jù)進(jìn)行 JSON 序列化輸出。
  • XML 數(shù)據(jù)直接輸出:
      func (this *AddController) Get() {
          mystruct := { ... }
          this.Data["xml"]=&mystruct
          this.ServeXML()
      }
    
    調(diào)用 ServeXML 之后,會(huì)設(shè)置 content-type 為 application/xml,同時(shí)數(shù)據(jù)會(huì)進(jìn)行 XML 序列化輸出。
  • jsonp 調(diào)用:
      func (this *AddController) Get() {
          mystruct := { ... }
          this.Data["jsonp"] = &mystruct
          this.ServeJSONP()
      }
    
    調(diào)用 ServeJSONP 之后,會(huì)設(shè)置 content-type 為 application/javascript,然后同時(shí)把數(shù)據(jù)進(jìn)行 JSON 序列化,然后根據(jù)請(qǐng)求的 callback 參數(shù)設(shè)置 jsonp 輸出。

開發(fā)模式下序列化后輸出的是格式化易閱讀的 JSON 或 XML 字符串;在生產(chǎn)模式下序列化后輸出的是壓縮的字符串。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)