加入收藏 | 设为首页 | 会员中心 | 我要投稿 南通站长网 (https://www.0513zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 网站设计 > 教程 > 正文

优雅的读取http请求或响应的数据

发布时间:2019-02-02 09:10:33 所属栏目:教程 来源:戚银
导读:副标题#e# 从 http.Request.Body 或 http.Response.Body 中读取数据方法或许很多,标准库中大多数使用 ioutil.ReadAll 方法一次读取所有数据,如果是 json 格式的数据还可以使用 json.NewDecoder 从 io.Reader 创建一个解析器,假使使用 pprof 来分析程序总

而且序列化之后会进行一次数据拷贝:

  1. func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) { 
  2.     stream := cfg.BorrowStream(nil) 
  3.     defer cfg.ReturnStream(stream) 
  4.     stream.WriteVal(v) 
  5.     if stream.Error != nil { 
  6.         return nil, stream.Error 
  7.     } 
  8.     result := stream.Buffer() 
  9.     copied := make([]byte, len(result)) 
  10.     copy(copied, result) 
  11.     return copied, nil 

既然要用 buffer 那就一起吧^_^,这样可以减少多次内存分配,下读取 http.Response.Body 之前一定要记得 buffer.Reset(), 这样基本就已经完成了 http.Request.Body 和 http.Response.Body 的数据读取优化了,具体效果等上线跑一段时间稳定之后来查看吧。

效果分析

上线跑了一天,来看看效果吧。

  1. $ go tool pprof allocs2 
  2. File: connect_server 
  3. Type: alloc_space 
  4. Time: Jan 26, 2019 at 10:27am (CST) 
  5. Entering interactive mode (type "help" for commands, "o" for options) 
  6. (pprof) top 
  7. Showing nodes accounting for 295.40GB, 40.62% of 727.32GB total 
  8. Dropped 738 nodes (cum <= 3.64GB) 
  9. Showing top 10 nodes out of 174 
  10.       flat  flat%   sum%        cum   cum% 
  11.    73.52GB 10.11% 10.11%    73.52GB 10.11%  git.tvblack.com/tvblack/connect_server/vendor/github.com/sirupsen/logrus.(*Entry).WithFields 
  12.    31.70GB  4.36% 14.47%    31.70GB  4.36%  net/url.unescape 
  13.    27.49GB  3.78% 18.25%    54.87GB  7.54%  git.tvblack.com/tvblack/connect_server/models.LogItemsToBytes 
  14.    27.41GB  3.77% 22.01%    27.41GB  3.77%  strings.Join 
  15.    25.04GB  3.44% 25.46%    25.04GB  3.44%  bufio.NewWriterSize 
  16.    24.81GB  3.41% 28.87%    24.81GB  3.41%  bufio.NewReaderSize 
  17.    23.91GB  3.29% 32.15%    23.91GB  3.29%  regexp.(*bitState).reset 
  18.    23.06GB  3.17% 35.32%    23.06GB  3.17%  math/big.nat.make 
  19.    19.90GB  2.74% 38.06%    20.35GB  2.80%  git.tvblack.com/tvblack/connect_server/vendor/github.com/json-iterator/go.(*Iterator).readStringSlowPath 
  20.    18.58GB  2.56% 40.62%    19.12GB  2.63%  net/textproto.(*Reader).ReadMIMEHeader 

(编辑:南通站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读