Simplest way to return literal JSON using gin gonic

11,342

Solution 1

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

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

Solution 2

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.

Share:
11,342
tritium_3
Author by

tritium_3

Updated on June 05, 2022

Comments

  • tritium_3
    tritium_3 almost 2 years

    I am learning Go by building a simple API interface for a web server. I want to return a simple message in JSON, when a default route is hit.

    So far, reading online, this is the easiest way to return a literal JSON string, and encode it and send it to the user.

    func GetDefault(c *gin.Context)  {
        jsonData := []byte(`{"msg":"this worked"}`)
    
        var v interface{}
        json.Unmarshal(jsonData, &v)
        data := v.(map[string]interface{})  
    
        c.JSON(http.StatusOK,data)
    }
    

    Is this the most efficient / fastest way to do it?

    in node.js and express, I would do something like:

    return res.status(200).json({"msg":"this worked"});
    

    Whats the best way to do this in Go + Gin?

  • Gwyneth Llewelyn
    Gwyneth Llewelyn about 2 years
    Since, from context, it's clear that the OP is using the Gin Gonic framework, this answer represents the best, idiomatic way to do it under Gin. The other answers may be 'correct', strictly speaking, but they're not 'best practices' for those who use Gin Gonic.
  • Gwyneth Llewelyn
    Gwyneth Llewelyn about 2 years
    While all your answers are technically correct, it seems overkill to have so much effort put into sending a JSON-formatted string, when Context.JSON() does that job effortlessly...