XML, JSON 和 YAML 渲染

  1. func main() {
  2. r := gin.Default()
  3. // gin.H 是一个 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. // 你也可以使用一个结构
  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. // 注意 msg.Name 在 JSON 中会变成 "user"
  18. // 将会输出: {"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. // 监听并服务于 0.0.0.0:8080
  28. r.Run(":8080")
  29. }

SecureJSON

使用 SecureJSON 来防止 json 劫持。如果给定的结构体是数组值,默认预置 "while(1)," 到 response body 。

  1. func main() {
  2. r := gin.Default()
  3. // 你也可以使用自己的安装 json 前缀
  4. // r.SecureJsonPrefix(")]}',\n")
  5. r.GET("/someJSON", func(c *gin.Context) {
  6. names := []string{"lena", "austin", "foo"}
  7. // 将会输出 : while(1);["lena","austin","foo"]
  8. c.SecureJSON(http.StatusOK, names)
  9. })
  10. // 监听并服务于 0.0.0.0:8080
  11. r.Run(":8080")
  12. }

JSONP

在不同的域中使用 JSONP 从一个服务器请求数据。如果请求参数中存在 callback,添加 callback 到 response body 。

  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 是 x
  8. // 将会输出 : x({\"foo\":\"bar\"})
  9. c.JSONP(http.StatusOK, data)
  10. })
  11. // 监听并服务于 0.0.0.0:8080
  12. r.Run(":8080")
  13. }