亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang 框架 beego ServeJSON的數據到底應該用什么類型?

golang 框架 beego ServeJSON的數據到底應該用什么類型?

蝴蝶刀刀 2019-03-12 19:37:59
mystruct := &JSONStruct{0, "hello"} fmt.Println(mystruct)c.Data["json"] = mystructc.ServeJSON()按以上寫法是通過的但是mystruct := JSONStruct{0, "hello"}這樣寫也可以通過到底哪種合理?
查看完整描述

2 回答

?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

我沒有太理解你的問題, 你是想問 c.Data["json"] 是 JSONStruct的值和指針的區別嗎, 為什么用指針和值都可以得到正確的輸出?這個問題我建議你看 c.ServeJSON()的源碼就明白了

查看完整回答
反對 回復 2019-03-12
?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

// ServeJson sends a json response with encoding charset.func (c *Controller) ServeJson(encoding ...bool) {    var hasIndent bool
    var hasencoding bool
    if RunMode == "prod" {
        hasIndent = false
    } else {
        hasIndent = true
    }    if len(encoding) > 0 && encoding[0] == true {
        hasencoding = true
    }
    c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
}// Json writes json to response body.// if coding is true, it converts utf-8 to \u0000 type.func (output *BeegoOutput) Json(data interface{}, hasIndent bool, coding bool) error {
    output.Header("Content-Type", "application/json; charset=utf-8")    var content []byte
    var err error    if hasIndent {
        content, err = json.MarshalIndent(data, "", "  ")
    } else {
        content, err = json.Marshal(data)
    }    if err != nil {
        http.Error(output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)        return err
    }    if coding {
        content = []byte(stringsToJson(string(content)))
    }
    output.Body(content)    return nil}

實際這個方法是對json序列化和 http 響應的封裝, 只是直接把 c.Data["json"] 傳遞給json組件了而已, json 內部會進行反射, 會自動處理指針類型的數據,和我們平時使用沒有任何區別, 只要是 json組件可以序列化的數據都可以給 c.Data["json"] ,而 c.Data 是 map[interface{}]interface{} 類型的數據


查看完整回答
反對 回復 2019-03-12
  • 2 回答
  • 0 關注
  • 1790 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號