成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

兩種方法實現 Http Request Body 多次讀取

開發 前端
在 gin 中, 在讀取了 request body 后, 通過 c.Set(BodyBytesKey, body) 放到了 gin.Context 中的 Keys。這是一個 map, 上面說到了。

大家好, 我是 老麥, 一個運維老兵, 現在專注于 Golang,DevOps,云原生基礎設施建設。

原文鏈接: https://typonotes.com/posts/2024/01/02/http-request-multiple-times-read/

最近在使用 gin 的時候, 踩了一個重復讀取的 Request.Body 的坑。

起因是 gin 的 gin.Context{} 提供了 c.Copy() 方法創建副本。這個方法一直在用, 但不知道從什么時候開始, 一直認為這個方法是 深拷貝, 但 并不完全是 (T_T)

// Copy returns a copy of the current context that can be safely used outside the request's scope.
// This has to be used when the context has to be passed to a goroutine.
func (c *Context) Copy() *Context {
 cp := Context{
  writermem: c.writermem,
  Request:   c.Request, // 指針, 也算引用類型。 沒有實現完全復制
  Params:    c.Params,
  engine:    c.engine,
 }
 cp.writermem.ResponseWriter = nil
 cp.Writer = &cp.writermem
 cp.index = abortIndex
 cp.handlers = nil
 cp.Keys = map[string]interface{}{} // Keys 完全復制
 for k, v := range c.Keys {
  cp.Keys[k] = v
 }
 paramCopy := make([]Param, len(cp.Params)) // 切片, 完全復制
 copy(paramCopy, cp.Params) 
 cp.Params = paramCopy
 return &cp
}

1. gin 通過用一個全局變量保存

在 gin 中, 在讀取了 request body 后, 通過 c.Set(BodyBytesKey, body) 放到了 gin.Context 中的 Keys。這是一個 map, 上面說到了。

因此 在 gin 中通過中間變量實現類似效果。雖然感覺上多次讀取 Body , 但實際 只讀取了一次,

// ShouldBindBodyWith is similar with ShouldBindWith, but it stores the request
// body into the context, and reuse when it is called again.
//
// NOTE: This method reads the body before binding. So you should use
// ShouldBindWith for better performance if you need to call only once.
func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error) {
 var body []byte
 if cb, ok := c.Get(BodyBytesKey); ok {
  if cbb, ok := cb.([]byte); ok {
   body = cbb
  }
 }
 if body == nil {
  body, err = io.ReadAll(c.Request.Body)
  if err != nil {
   return err
  }
  // 將 Body 中的內容放到 gin.Context 中的 Keys 中
  c.Set(BodyBytesKey, body)
 }
 return bb.BindBody(body, obj)
}

參考文檔: https://github.com/gin-gonic/gin/blob/v1.9.1/context.go#L744-L764

2. 再造一個 Request

另外一種方法, 就是在讀取 Body 后, 重建一個 Requset 再把 Body 放進去。

// 讀取老的
body, err := ioutil.ReadAll(r.Body)
if err != nil {
    // ...
}
url, _ := url.Parse(config.GetGameHost())

// 創建新的
r2 := r.Clone(r.Context())

// 將數據方進去
r.Body = ioutil.NopCloser(bytes.NewReader(body))
r2.Body = ioutil.NopCloser(bytes.NewReader(body))

r.ParseForm()

proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ServeHTTP(w, r2)

參考文檔: https://stackoverflow.com/q/62017146

注意 http.Request 有一個方法叫 Clone(), 但這也不是一個完全的深拷貝。Body 沒有復制。

// Clone returns a deep copy of r with its context changed to ctx.
// The provided ctx must be non-nil.
//
// For an outgoing client request, the context controls the entire
// lifetime of a request and its response: obtaining a connection,
// sending the request, and reading the response headers and body.
func (r *Request) Clone(ctx context.Context) *Request {
 if ctx == nil {
  panic("nil context")
 }
 r2 := new(Request)
 *r2 = *r
 r2.ctx = ctx
 r2.URL = cloneURL(r.URL)
 if r.Header != nil {
  r2.Header = r.Header.Clone()
 }
 if r.Trailer != nil {
  r2.Trailer = r.Trailer.Clone()
 }
 if s := r.TransferEncoding; s != nil {
  s2 := make([]string, len(s))
  copy(s2, s)
  r2.TransferEncoding = s2
 }
 r2.Form = cloneURLValues(r.Form)
 r2.PostForm = cloneURLValues(r.PostForm)
 r2.MultipartForm = cloneMultipartForm(r.MultipartForm)
 return r2
}
責任編輯:武曉燕 來源: 熊貓云原生Go
相關推薦

2010-07-26 15:42:34

Perl模塊

2009-09-25 14:04:09

Hibernate eHibernate h

2010-08-02 16:58:08

Flex配置文件

2010-08-03 13:53:47

Flex+Java配置

2009-08-05 15:54:49

Web Service

2010-08-04 17:41:52

掛載NFS

2010-05-28 10:35:46

SVN搭建測試服務器

2010-06-02 17:16:16

自動運行SVN

2009-11-03 16:20:16

VB.NET文本框

2009-04-21 11:23:56

Oraclespool比較

2010-06-17 12:48:05

livecd 修復Gr

2010-04-13 09:50:44

Oracle跟蹤

2009-11-06 09:48:40

WCF服務

2010-05-26 18:52:12

SVN庫

2010-11-24 14:36:25

修復mysql表

2011-03-30 17:04:24

MySQL添加用戶

2009-08-03 17:53:11

XML數據

2010-09-13 13:05:03

sql server分

2010-11-10 13:22:41

SQL Server備

2010-11-09 13:09:58

SQL Server分
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 成人在线精品视频 | 天堂久| 日日日色 | 在线国产中文字幕 | 亚洲www啪成人一区二区麻豆 | 在线观看欧美一区 | 国产精品日韩欧美一区二区三区 | 中文字幕一区二区三区乱码在线 | 日韩成人免费中文字幕 | 伊人狠狠干| 综合久久一区 | 欧美日韩中文字幕在线播放 | 中文字幕亚洲专区 | 中文字幕蜜臀 | 欧美一级免费片 | 国产一区二区在线免费播放 | 欧美激情在线一区二区三区 | 国产 日韩 欧美 中文 在线播放 | 国产精品视频97 | a欧美| 国产精品一区视频 | 黄网站色大毛片 | 亚洲视频在线播放 | 99中文字幕 | 日韩欧美网 | 视频国产一区 | 久久久.com | 91人人澡人人爽 | 欧美日韩黄 | 亚洲视频一区在线播放 | 国产成人精品午夜视频免费 | 啪一啪| 超碰高清| 国产精品免费在线 | 国产一级精品毛片 | 99久久免费精品国产男女高不卡 | www.色.com| 91视频官网| 亚洲女人天堂成人av在线 | 欧美性受| 一级片av|