gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
79.17k stars 8.03k forks source link

[Question] Render msgpack? #2439

Open worldadmin opened 4 years ago

worldadmin commented 4 years ago

How to set response in msgpack like this https://github.com/gin-gonic/gin#xml-json-yaml-and-protobuf-rendering ?

hooting commented 3 years ago

Add a method to Context in file https://github.com/gin-gonic/gin/blob/master/context.go

func (c *Context) Msgpack(code int, obj interface{}) {
    c.Render(code, render.MsgPack{Data: obj})
}

then, you can response in msgpack:

func main() {
    r := gin.Default()

    // gin.H is a shortcut for map[string]interface{}
    r.GET("/someMsgpack", func(c *gin.Context) {
        c.Msgpack(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
    })

    // Listen and serve on 0.0.0.0:8080
    r.Run(":8080")
}