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()的源碼就明白了

胡子哥哥
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{}
類型的數據
- 2 回答
- 0 關注
- 1790 瀏覽
添加回答
舉報
0/150
提交
取消