XML, JSON and YAML rendering

  1. func main() {
  2. r := gin.Default()
  3. // gin.H is a shortcut for map[string]interface{}
  4. r.GET("/someJSON", func(c *gin.Context) {
  5. c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  6. })
  7. r.GET("/moreJSON", func(c *gin.Context) {
  8. // You also can use a struct
  9. var msg struct {
  10. Name string `json:"user"`
  11. Message string
  12. Number int
  13. }
  14. msg.Name = "Lena"
  15. msg.Message = "hey"
  16. msg.Number = 123
  17. // Note that msg.Name becomes "user" in the JSON
  18. // Will output : {"user": "Lena", "Message": "hey", "Number": 123}
  19. c.JSON(http.StatusOK, msg)
  20. })
  21. r.GET("/someXML", func(c *gin.Context) {
  22. c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  23. })
  24. r.GET("/someYAML", func(c *gin.Context) {
  25. c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  26. })
  27. // Listen and serve on 0.0.0.0:8080
  28. r.Run(":8080")
  29. }

SecureJSON

Using SecureJSON to prevent json hijacking. Default prepends "while(1)," to response body if the given struct is array values.

  1. func main() {
  2. r := gin.Default()
  3. // You can also use your own secure json prefix
  4. // r.SecureJsonPrefix(")]}',\n")
  5. r.GET("/someJSON", func(c *gin.Context) {
  6. names := []string{"lena", "austin", "foo"}
  7. // Will output : while(1);["lena","austin","foo"]
  8. c.SecureJSON(http.StatusOK, names)
  9. })
  10. // Listen and serve on 0.0.0.0:8080
  11. r.Run(":8080")
  12. }

JSONP

Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/JSONP?callback=x", func(c *gin.Context) {
  4. data := map[string]interface{}{
  5. "foo": "bar",
  6. }
  7. //callback is x
  8. // Will output : x({\"foo\":\"bar\"})
  9. c.JSONP(http.StatusOK, data)
  10. })
  11. // Listen and serve on 0.0.0.0:8080
  12. r.Run(":8080")
  13. }

AsciiJSON

Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII chracters.

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/someJSON", func(c *gin.Context) {
  4. data := map[string]interface{}{
  5. "lang": "GO语言",
  6. "tag": "<br>",
  7. }
  8. // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}
  9. c.AsciiJSON(http.StatusOK, data)
  10. })
  11. // Listen and serve on 0.0.0.0:8080
  12. r.Run(":8080")
  13. }