banner
biuaxia

biuaxia

"万物皆有裂痕,那是光进来的地方。"
github
bilibili
tg_channel

【轉載】golang複用http.request.body

title: 【轉載】golang 複用 http.request.body
date: 2021-07-06 11:14:22
comment: false
toc: true
category:

  • Golang
    tags:
  • 轉載
  • Go
  • golang
  • 複用
  • http
  • request
  • body

本文轉載自:golang 複用 http.request.body - Go 語言中文網 - Golang 中文社區


問題及場景#

業務當中有需要分發 http.request.body 的場景。比如微信回調消息只能指定一個地址,所以期望可以複製一份消息發給其他服務。由服務 B 和接收微信回調的服務 A 一起處理微信回調信息。

解決思路#

最開始考慮的是直接轉發 http.request。使用ReverseProxy直接將 http.request 由服務 A 轉發給服務 B。但是微信涉及到驗證等問題,完全調整好非常麻煩。所以轉換思路,打算將 http.request.body 的內容直接 post 給服務 B。

可是 http.request 是 readcloser。我們將 http.request readAll 的時候將無法再次讀取 http.request 裡面的信息。

如何才能將 http.request.body 複製使用呢?#

其中 c 表示的是 http 的上下文

    // 把request的內容讀取出來
    var bodyBytes []byte
    if c.Request.Body != nil {
        bodyBytes, _ = ioutil.ReadAll(c.Request.Body)
    }
    // 把剛剛讀出來的再寫進去
    c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

1. 我們先將 body 從 http.request 裡面讀取出來,保存到一個變量裡面。

2. 然後再將變量裡面的數據使用 ioutil.NopCloser 方法寫回到 http.request 裡面。

https://golang.org/pkg/io/ioutil/#NopCloser

NopCloser 返回一個 ReadCloser 接口,該接口具有一個無操作的 Close 方法,包裝了提供的 Reader r。

這樣我們就可以再次使用 c.request 來進行處理了。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。