IDC

Golang GinWeb框架5-XML/JSON/YAML/ProtoBuf等渲染

作者:admin 2021-09-20 我要评论

简介 本文接着上文(Golang GinWeb框架5-绑定请求字符串/URI/请求头/复选框/表单类型)继续探索GinWeb框架。 XML,JSON,YAML,ProtoBuf等渲染 packagemain import( g...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

 简介

本文接着上文(Golang GinWeb框架5-绑定请求字符串/URI/请求头/复选框/表单类型)继续探索GinWeb框架。

XML,JSON,YAML,ProtoBuf等渲染

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "github.com/gin-gonic/gin/testdata/protoexample" 
  6.   "net/http" 
  7.  
  8. func main() { 
  9.   r := gin.Default() 
  10.  
  11.   // gin.H is a shortcut for map[string]interface{} 
  12.   // gin.H对象是一个map映射,键名为字符串类型, 键值是接口,所以可以传递所有的类型 
  13.   r.GET("/someJSON", func(c *gin.Context) { 
  14.     c.JSON(http.StatusOK, gin.H{"message""hey""status": http.StatusOK}) 
  15.   }) 
  16.  
  17.   r.GET("/moreJSON", func(c *gin.Context) { 
  18.     // You also can use a struct 
  19.     var msg struct { 
  20.       Name    string `json:"user"
  21.       Message string 
  22.       Number  int 
  23.     } 
  24.     msg.Name = "Lena" 
  25.     msg.Message = "hey" 
  26.     msg.Number = 123 
  27.     // Note that msg.Name becomes "user" in the JSON 
  28.     // Will output  :   {"user""Lena""Message""hey""Number": 123} 
  29.  
  30.     //JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json"
  31.     //JSON方法将给定的结构序列化为JSON到响应体, 并设置内容类型Content-Type为:"application/json" 
  32.     c.JSON(http.StatusOK, msg) 
  33.   }) 
  34.  
  35.   r.GET("/someXML", func(c *gin.Context) { 
  36.     c.XML(http.StatusOK, gin.H{"message""hey""status": http.StatusOK}) 
  37.   }) 
  38.  
  39.   r.GET("/someYAML", func(c *gin.Context) { 
  40.     c.YAML(http.StatusOK, gin.H{"message""hey""status": http.StatusOK}) 
  41.   }) 
  42.  
  43.   //Protocol buffers are a language-neutral, platform-neutral extensible mechanism for serializing structured data. 
  44.   //Protocol buffers(简称ProtoBuf)是来自Google的一个跨语言,跨平台,用于将结构化数据序列化的可扩展机制, 
  45.   //详见:https://developers.google.com/protocol-buffers 
  46.   r.GET("/someProtoBuf", func(c *gin.Context) { 
  47.     reps := []int64{int64(1), int64(2)} 
  48.     label := "test" 
  49.     // The specific definition of protobuf is written in the testdata/protoexample file. 
  50.     // 使用protoexample.Test这个特别的protobuf结构来定义测试数据 
  51.     data := &protoexample.Test{ 
  52.       Label: &label, 
  53.       Reps:  reps, 
  54.     } 
  55.     // Note that data becomes binary data in the response  //将data序列化为二进制的响应数据 
  56.     // Will output protoexample.Test protobuf serialized data 
  57.     // ProtoBuf serializes the given struct as ProtoBuf into the response body. 
  58.     // ProtoBuf方法将给定的结构序列化为ProtoBuf响应体 
  59.     c.ProtoBuf(http.StatusOK, data) 
  60.   }) 
  61.  
  62.   // Listen and serve on 0.0.0.0:8080 
  63.   r.Run(":8080"
  64.  
  65. /* 
  66. 模拟测试 
  67. curl http://localhost:8080/someJSON 
  68. {"message":"hey","status":200} 
  69.  
  70. curl http://localhost:8080/moreJSON 
  71. {"user":"Lena","Message":"hey","Number":123} 
  72.  
  73. curl http://localhost:8080/someXML 
  74. <map><message>hey</message><status>200</status></map> 
  75.  
  76. curl http://localhost:8080/someYAML 
  77. message: hey 
  78. status: 200 
  79.  
  80. curl http://localhost:8080/someProtoBuf 
  81. test 
  82. */ 

安全的JSOn

使用SecureJSON方法保护Json不被劫持, 如果响应体是一个数组, 该方法会默认添加`while(1)`前缀到响应头, 这样的死循环可以防止后面的代码被恶意执行, 也可以自定义安全JSON的前缀.

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "net/http" 
  6.  
  7. func main() { 
  8.   r := gin.Default() 
  9.  
  10.   // You can also use your own secure json prefix 
  11.   // 你也可以自定义安全Json的前缀 
  12.   r.SecureJsonPrefix(")]}',\n"
  13.  
  14.   //使用SecureJSON方法保护Json不被劫持, 如果响应体是一个数组, 该方法会默认添加`while(1)`前缀到响应头,  这样的死循环可以防止后面的代码被恶意执行, 也可以自定义安全JSON的前缀. 
  15.   r.GET("/someJSON", func(c *gin.Context) { 
  16.     names := []string{"lena""austin""foo"
  17.  
  18.     //names := map[string]string{ 
  19.     //  "hello""world"
  20.     //} 
  21.  
  22.     // Will output  :   while(1);["lena","austin","foo"
  23.     c.SecureJSON(http.StatusOK, names) 
  24.   }) 
  25.  
  26.   // Listen and serve on 0.0.0.0:8080 
  27.   r.Run(":8080"
  28.  
  29. /* 
  30. 模拟请求:curl http://localhost:8080/someJSON 
  31. )]}', 
  32. ["lena","austin","foo"]% 
  33. */ 

JSONP

使用JSONP可以实现跨域请求数据, 如果请求中有查询字符串参数callback, 则将返回数据作为参数传递给callback值(前端函数名),整体作为一个响应体,返回给前端.

JSONP是服务器与客户端跨源通信的常用方法. 最大特点就是简单适用, 老式浏览器全部支持, 服务器改造非常小, 它的基本思想是: 网页通过添加一个<script>元素, 向服务器请求JSON数据, 这种做法不受同源政策限制, 服务器收到请求后, 将数据放在一个指定名字的回调函数里传回来, 这样, 前端可以完成一次前端函数的调用, 而参数是后端返回的数据.

注意: 这种方式存在被劫持的风险

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "net/http" 
  6.  
  7. func main() { 
  8.   r := gin.Default() 
  9.  
  10.   r.GET("/JSONP", func(c *gin.Context) { 
  11.     data := gin.H{ 
  12.       "foo""bar"
  13.     } 
  14.  
  15.     //callback is x 
  16.     // Will output  :   x({\"foo\":\"bar\"}) 
  17.     // 使用JSONP可以实现跨域请求数据, 如果请求中有查询字符串参数callback, 则将返回数据作为参数传递给callback值(前端函数名),整体作为一个响应体,返回给前端 
  18.     //JSONP是服务器与客户端跨源通信的常用方法。最大特点就是简单适用,老式浏览器全部支持,服务器改造非常小。 
  19.     //它的基本思想是,网页通过添加一个<script>元素,向服务器请求JSON数据,这种做法不受同源政策限制;服务器收到请求后,将数据放在一个指定名字的回调函数里传回来 
  20.     c.JSONP(http.StatusOK, data) 
  21.   }) 
  22.  
  23.   // Listen and serve on 0.0.0.0:8080 
  24.   r.Run(":8080"
  25.  
  26.   // 模拟客户端,请求参数中有callback参数,值为x(前端函数名),最后响应内容为x("foo":"bar"
  27.   // curl http://127.0.0.1:8080/JSONP?callback=x 

AsciiJSON

使用ASCII编码, 将非ASCII的字符进行转义和编码, 生成纯ASCII编码的JSON

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "net/http" 
  6.  
  7. func main() { 
  8.   r := gin.Default() 
  9.  
  10.   r.GET("/someJSON", func(c *gin.Context) { 
  11.     data := gin.H{ 
  12.       "lang""GO语言"
  13.       "tag":  "<br>"
  14.     } 
  15.  
  16.     // 输出结果 : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"
  17.     // AsciiJSON方法返回带有Unicode编码和转义组成的纯ASCII字符串 
  18.     c.AsciiJSON(http.StatusOK, data) 
  19.   }) 
  20.  
  21.   // Listen and serve on 0.0.0.0:8080 
  22.   r.Run(":8080"
  23.  
  24. /* 
  25. 模拟请求:curl http://localhost:8080/someJSON 
  26.  */ 

不带转义的原始JSON

通常, JSON会将特殊的HTML字符转化为他们的unicode编码, 如标签`<`转为`\u003c` 使用PureJSON方法可以得到原始不做转义的字符串.

注意: 该方法至少需要Go版本1.6以上

  1. package main 
  2.  
  3. import "github.com/gin-gonic/gin" 
  4.  
  5. func main() { 
  6.   r := gin.Default() 
  7.  
  8.   // Serves unicode entities 
  9.   r.GET("/json", func(c *gin.Context) { 
  10.     c.JSON(200, gin.H{ 
  11.       "html""<b>Hello, world!</b>"
  12.     }) 
  13.   }) 
  14.  
  15.   // Serves literal characters 
  16.   r.GET("/purejson", func(c *gin.Context) { 
  17.     c.PureJSON(200, gin.H{ 
  18.       "html""<b>Hello, world!</b>"
  19.     }) 
  20.   }) 
  21.  
  22.   // listen and serve on 0.0.0.0:8080 
  23.   r.Run(":8080"
  24. /* 
  25. 模拟请求,得到将HTML标签转义后的JSON字符串 
  26. curl http://localhost:8080/json 
  27. {"html":"\u003cb\u003eHello, world!\u003c/b\u003e"}                                                                                                                                                                            
  28. 得到原始JSON字符串 
  29. curl http://localhost:8080/purejson 
  30. {"html":"<b>Hello, world!</b>"
  31. */ 

参考文档

Gin官方仓库:https://github.com/gin-gonic/gin


本文转载自网络,原文链接:https://mp.weixin.qq.com/s/Vyql-K4lvxY3eZkBeFPS_A

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • Golang GinWeb框架5-XML/JSON/YAML/Pro

    Golang GinWeb框架5-XML/JSON/YAML/Pro

  • 我点击页面元素,为什么VSCode乖乖打开

    我点击页面元素,为什么VSCode乖乖打开

  • Java高级特性-注解:注解实现Excel导出

    Java高级特性-注解:注解实现Excel导出

  • 手把手教你实现一个Vue无限级联树形表

    手把手教你实现一个Vue无限级联树形表

腾讯云代理商
海外云服务器