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?
gin. Default() creates a Gin router with default middleware: logger and recovery middleware. Next, we make a handler using router. GET(path, handle) , where path is the relative path, and handle is the handler function that takes *gin. Context as an argument.
Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to httprouter. If you need performance and good productivity, you will love Gin.
It features a Martini-like API with much better performance that is up to 40 times faster. Gin Gonic can be primarily classified as “Frameworks (Full Stack)” tools. SpartanGeek, Sezzle, and SEASON are some of the popular companies that use Gin Gonic.
Returns the specified key from a POST urlencoded form or multipart form when it exists, otherwise it returns the specified defaultValue string. func SomeHandler(c *gin. Context) { key := c. PostForm("key", "default value")
you can use the gin.H
struct on you response:
c.JSON(http.StatusOK, gin.H{"msg":"this worked"})
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With