undefinedfix
Sign in

What kind of data should be used in the golang framework beego servejson?

Deketh edited in Fri, 01 Jul 2022
mystruct := &JSONStruct{0, "hello"}
fmt.Println(mystruct)
c.Data["json"] = mystruct
c.ServeJSON()

According to the above, it is passed, but

mystruct := JSONStruct{0, "hello"}

This writing can also be passed. Which is reasonable?

1 Replies
Amer
commented on Fri, 01 Jul 2022

I don't quite understand your question. Do you want to ask C. data ["JSON"] is the difference between the value and pointer of jsonstruct? Why can we get the correct output with both pointer and value? I suggest you look at the source code of C. servejson()

// 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
}

In fact, this method encapsulates the JSON serialization and HTTP response. It just passes c.data ["JSON"] to the JSON component directly. The internal part of the JSON will reflect and automatically process pointer type data. It is no different from our usual use. As long as the data that can be serialized by the JSON component can be sent to c.data ["JSON"], and c.data is Data of type map [interface {}] interface {}

lock This question has been locked and the reply function has been disabled.