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

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

发布时间:2019-01-31 03:33:43 所属栏目:教程 来源:戚银
导读:从 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 

(编辑:湖南网)

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

热点阅读