Simplest way to return literal JSON using gin gonic

One option is to use Context.Data() where you provide the data to send (along with the content type):

func GetDefault(c *gin.Context)  {
    jsonData := []byte(`{"msg":"this worked"}`)

    c.Data(http.StatusOK, "application/json", jsonData)
}

You may also use a constant for the content type:

func GetDefault(c *gin.Context)  {
    jsonData := []byte(`{"msg":"this worked"}`)

    c.Data(http.StatusOK, gin.MIMEJSON, jsonData)
}

If your data is availabe as a string value and is big, you can avoid converting it to []byte if you use Context.DataFromReader():

func GetDefault(c *gin.Context) {
    jsonStr := `{"msg":"this worked"}`

    c.DataFromReader(http.StatusOK,
        int64(len(jsonStr)), gin.MIMEJSON, strings.NewReader(jsonStr), nil)
}

This solution also works if you have your JSON as an io.Reader, e.g. an os.File.


you can use the gin.H struct on you response:

c.JSON(http.StatusOK, gin.H{"msg":"this worked"})