XML、JSON、YAML和ProtoBuf 渲染(输出格式)

最后更新于:2022-04-02 07:26:47

即接口返回的数据格式 ``` func main() { r := gin.Default() // gin.H is a shortcut for map[string]interface{} r.GET("/someJSON", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/moreJSON", func(c *gin.Context) { // You also can use a struct var msg struct { Name string `json:"user"` Message string Number int } msg.Name = "Lena" msg.Message = "hey" msg.Number = 123 // Note that msg.Name becomes "user" in the JSON // Will output : {"user": "Lena", "Message": "hey", "Number": 123} c.JSON(http.StatusOK, msg) }) r.GET("/someXML", func(c *gin.Context) { c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someYAML", func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK}) }) r.GET("/someProtoBuf", func(c *gin.Context) { reps := []int64{int64(1), int64(2)} label := "test" // The specific definition of protobuf is written in the testdata/protoexample file. data := &protoexample.Test{ Label: &label, Reps: reps, } // Note that data becomes binary data in the response // Will output protoexample.Test protobuf serialized data c.ProtoBuf(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` **SecureJSON** 使用SecureJSON可以防止json劫持,如果返回的数据是数组,则会默认在返回值前加上`"while(1)"` ``` func main() { r := gin.Default() // 可以自定义返回的json数据前缀 // r.SecureJsonPrefix(")]}',\n") r.GET("/someJSON", func(c *gin.Context) { names := []string{"lena", "austin", "foo"} // 将会输出: while(1);["lena","austin","foo"] c.SecureJSON(http.StatusOK, names) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` **JSONP** 使用JSONP可以跨域传输,如果参数中存在回调参数,那么返回的参数将是回调函数的形式 ``` func main() { r := gin.Default() r.GET("/JSONP", func(c *gin.Context) { data := map[string]interface{}{ "foo": "bar", } // 访问 http://localhost:8080/JSONP?callback=call // 将会输出: call({foo:"bar"}) c.JSONP(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` **AsciiJSON** 使用AsciiJSON将使特殊字符编码 ``` func main() { r := gin.Default() r.GET("/someJSON", func(c *gin.Context) { data := map[string]interface{}{ "lang": "GO语言", "tag": "
", } // 将输出: {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"} c.AsciiJSON(http.StatusOK, data) }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") } ``` **PureJSON** 通常情况下,JSON会将特殊的HTML字符替换为对应的unicode字符,比如`<`替换为`\u003c`,如果想原样输出html,则使用PureJSON,这个特性在Go 1.6及以下版本中无法使用。 ``` func main() { r := gin.Default() // Serves unicode entities r.GET("/json", func(c *gin.Context) { c.JSON(200, gin.H{ "html": "Hello, world!", }) }) // Serves literal characters r.GET("/purejson", func(c *gin.Context) { c.PureJSON(200, gin.H{ "html": "Hello, world!", }) }) // listen and serve on 0.0.0.0:8080 r.Run(":8080") } ```
';