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 关注
- 1865 浏览
添加回答
举报
0/150
提交
取消
