如何讓 gin 正確讀取 http response body 內(nèi)容,并多次使用

我是 LEE,老李,一個在 IT 行業(yè)摸爬滾打 17 年的技術(shù)老兵。

事件背景

最近業(yè)務(wù)研發(fā)反應(yīng)了一個需求:能不能讓現(xiàn)有基于 gin 的 webservice 框架能夠自己輸出 response 的信息,尤其是 response body 內(nèi)容。因為研發(fā)在 QA 環(huán)境開發(fā)調(diào)試的時候,部署應(yīng)用大多數(shù)都是 debug 模式,不想在每一個 http handler 函數(shù)中總是手寫一個日志去記錄 response body 內(nèi)容,這樣做不但發(fā)布正式版本的時候要做清理,同時日常代碼維護也非常麻煩。如果 gin 的 webservice 框架能夠自己輸出 response 的信息到日志并記錄下來,這樣查看歷史應(yīng)用運行狀態(tài)、相關(guān)請求信息和定位請求異常時也比較方便。

針對這樣的需求,思考了下確實也是如此。平常自己寫服務(wù)的時候,本地調(diào)試用 Mock 數(shù)據(jù)各種沒有問題,但是一但進入到環(huán)境聯(lián)合調(diào)試的時候就各種問題,檢查服務(wù)接口在特定時間內(nèi)出入?yún)?shù)也非常不方便。如果 webservice 框架能夠把 request 和 response 相關(guān)信息全量作為日志存在 Elasticsearch 中,也方便回溯和排查。

要實現(xiàn)這個需求,用一個通用的 gin middleware 來做這個事情太合適了。并制作一個開關(guān),匹配 GIN_MODE 這個環(huán)境變量,能夠在部署時候自動開關(guān)這個功能,可以極大減少研發(fā)的心智負擔(dān)。

既然有這么多好處,說干就干。

心智負擔(dān)

通過對 gin 的代碼閱讀,發(fā)現(xiàn)原生 gin 框架沒有提供類似的功能,也說就要自己手寫一個。翻越了網(wǎng)上的解決方案,感覺都是淺淺說到了這個事情,但是沒有比較好的,且能夠應(yīng)用工程中的。所以一不做二不休,自己整理一篇文章來詳細說明這個問題。我相信用 gin 作為 webservice 框架的小伙伴應(yīng)該不少。

說到這里,又要從原代碼看起來,那么產(chǎn)生 response 的地方在哪里? 當(dāng)然是 http handler 函數(shù)。

這里先舉個例子:

func Demo(c *gin.Context) {
    var r = []string{"lee", "demo"}
    c.JSON(http.StatusOK, r)
}

這個函數(shù)返回內(nèi)容為:["lee","demo"] 。但是為了要將這個請求的 request 和 response 內(nèi)容記錄到日志中,就需要編寫類似如下的代碼。

func Demo(c *gin.Context) {
    var r = []string{"lee", "demo"}
    c.JSON(http.StatusOK, r)

    // 記錄相關(guān)的內(nèi)容
    b, _ := json.Marshal(r)
    log.Println("request: ", c.Request)
    log.Println("resposeBody: ", b)
}

各位小伙伴,嘗試想想每一個 http handler 函數(shù)都要你寫一遍,然后要針對運行環(huán)境是 QA 還是 Online 做判斷,或者在發(fā)布 Online 時候做代碼清理。我想研發(fā)小伙伴都會說:NO!! NO!! NO!!

前置知識

最好的辦法是將這個負擔(dān)交給 gin 的 webservice 框架來處理,研發(fā)不需要做相關(guān)的邏輯。居然要這么做,那么就要看看 gin 的 response 是怎么產(chǎn)生的。

用上面提到的 c.JSON 方法來舉例。

github.com/gin-gonic/gin@v1.8.1/context.go

// JSON serializes the given struct as JSON into the response body.
// It also sets the Content-Type as "application/json".
func (c *Context) JSON(code int, obj any) {
    c.Render(code, render.JSON{Data: obj})
}

這個 c.JSON 實際是 c.Render 的一個包裝函數(shù),繼續(xù)往下追。

github.com/gin-gonic/gin@v1.8.1/context.go

// Render writes the response headers and calls render.Render to render data.
func (c *Context) Render(code int, r render.Render) {
    c.Status(code)

    if !bodyAllowedForStatus(code) {
        r.WriteContentType(c.Writer)
        c.Writer.WriteHeaderNow()
        return
    }

    if err := r.Render(c.Writer); err != nil {
        panic(err)
    }
}

c.Render 還是一個包裝函數(shù),最終是用 r.Render 向 c.Writer 輸出數(shù)據(jù)。

github.com/gin-gonic/gin@v1.8.1/render/render.go

// Render interface is to be implemented by JSON, XML, HTML, YAML and so on.
type Render interface {
    // Render writes data with custom ContentType.
    Render(http.ResponseWriter) error
    // WriteContentType writes custom ContentType.
    WriteContentType(w http.ResponseWriter)
}

r.Render 是一個渲染接口,也就是 gin 可以輸出 JSON,XML,String 等等統(tǒng)一接口。 此時我們需要找 JSON 實現(xiàn)體的相關(guān)信息。

github.com/gin-gonic/gin@v1.8.1/render/json.go

// Render (JSON) writes data with custom ContentType.
func (r JSON) Render(w http.ResponseWriter) (err error) {
    if err = WriteJSON(w, r.Data); err != nil {
        panic(err)
    }
    return
}

// WriteJSON marshals the given interface object and writes it with custom ContentType.
func WriteJSON(w http.ResponseWriter, obj any) error {
    writeContentType(w, jsonContentType)
    jsonBytes, err := json.Marshal(obj)
    if err != nil {
        return err
    }
    _, err = w.Write(jsonBytes) // 寫入 response 內(nèi)容,內(nèi)容已經(jīng)被 json 序列化
    return err
}

追到這里,真正輸出內(nèi)容的函數(shù)是 WriteJSON,此時調(diào)用 w.Write(jsonBytes) 寫入被 json 模塊序列化完畢的對象。而這個 w.Write 是 http.ResponseWriter 的方法。那我們就看看 http.ResponseWriter 到底是一個什么樣子的?

net/http/server.go

// A ResponseWriter may not be used after the Handler.ServeHTTP method
// has returned.
type ResponseWriter interface {
    ...

    // Write writes the data to the connection as part of an HTTP reply.
    //
    // If WriteHeader has not yet been called, Write calls
    // WriteHeader(http.StatusOK) before writing the data. If the Header
    // does not contain a Content-Type line, Write adds a Content-Type set
    // to the result of passing the initial 512 bytes of written data to
    // DetectContentType. Additionally, if the total size of all written
    // data is under a few KB and there are no Flush calls, the
    // Content-Length header is added automatically.
    //
    // Depending on the HTTP protocol version and the client, calling
    // Write or WriteHeader may prevent future reads on the
    // Request.Body. For HTTP/1.x requests, handlers should read any
    // needed request body data before writing the response. Once the
    // headers have been flushed (due to either an explicit Flusher.Flush
    // call or writing enough data to trigger a flush), the request body
    // may be unavailable. For HTTP/2 requests, the Go HTTP server permits
    // handlers to continue to read the request body while concurrently
    // writing the response. However, such behavior may not be supported
    // by all HTTP/2 clients. Handlers should read before writing if
    // possible to maximize compatibility.
    Write([]byte) (int, error)

    ...
}

哦喲,最后還是回到了 golang 自己的 net/http 包了,看到 ResponseWriter 是一個 interface。那就好辦了,就不怕你是一個接口,我只要對應(yīng)的實現(xiàn)體給你不就能解決問題了嗎?好多人都是這么想的。

說得輕巧,這里有好幾個問題在面前:

  1. 什么樣的 ResponseWriter 實現(xiàn)才能解決問題?
  2. 什么時候傳入新的 ResponseWriter 覆蓋原有的 ResponseWriter 對象?
  3. 怎樣做代價最小,能夠減少對原有邏輯的入侵。能不能做到 100% 兼容原有邏輯?
  4. 怎么做才是最高效的做法,雖然是 debug 環(huán)境,但是 QA 環(huán)境不代表沒有流量壓力

解決思路

帶著上章中的問題,要真正的解決問題,就需要回到 gin 的框架結(jié)構(gòu)中去尋找答案。

追本溯源

gin 框架中的 middleware 實際是一個鏈條,并按照 Next() 的調(diào)用順序逐一往下執(zhí)行。

Next() 與執(zhí)行順序

middleware 執(zhí)行的順序會從最前面的 middleware 開始執(zhí)行,在 middleware function 中,一旦執(zhí)行 Next() 方法后,就會往下一個 middleware 的 function 走,但這并不表示 Next() 后的內(nèi)容不會被執(zhí)行到,相反的,Next()后面的內(nèi)容會等到所有 middleware function 中 Next() 以前的程式碼都執(zhí)行結(jié)束后,才開始執(zhí)行,并且由后往前逐一完成。

舉個例子,方便小伙伴理解:

func main() {
    router := gin.Default()
    router.GET("/api", func(c *gin.Context) {
        fmt.Println("First Middle Before Next")
        c.Next()
        fmt.Println("First Middle After Next")
    }, func(c *gin.Context) {
        fmt.Println("Second Middle Before Next")
        c.Next()
        fmt.Println("Second Middle After Next")
    }, func(c *gin.Context) {
        fmt.Println("Third Middle Before Next")
        c.Next()
        fmt.Println("Third Middle After Next")
        c.JSON(http.StatusOK, gin.H{
            "message": "pong",
        })
    })
}

Console 執(zhí)行結(jié)果如下:

// Next 之前的內(nèi)容會「由前往后」並且「依序」完成
First Middle Before Next
Second Middle Before Next
Third Middle Before Next

// Next 之后的內(nèi)容會「由后往前」並且「依序」完成
Third Middle After Next
Second Middle After Next
First Middle After Next

通過上面的例子,我們看到了 gin 框架中的 middleware 中處理流程。為了讓 gin 的 webservice 框架在后續(xù)的 middleware 中都能輕松獲得 func(c *gin.Context) 產(chǎn)生的 { "message": "pong" }, 就要結(jié)合上一章找到的 WriteJSON 函數(shù),讓其輸出到 ResponseWriter 的內(nèi)容保存到 gin 的 Context 中 (gin 框架中,每一個 http 回話都與一個 Context 對象綁定),這樣就可以在隨后的 middleware 能夠輕松訪問到 response body 中的內(nèi)容。

上手開發(fā)

還是回到上一章中的 4 個核心問題,我想到這里應(yīng)該有答案了:

  1. 構(gòu)建一個自定義的 ResponseWriter 實現(xiàn),覆蓋原有的 net/http 框架中 ResponseWriter,并實現(xiàn)對數(shù)據(jù)存儲。 -- 回答問題 1
  2. 攔截 c.JSON 底層 WriteJSON 函數(shù)中的 w.Write 方法,就可以對框架無損。 -- 回答問題 2,3
  3. 在 gin.Use() 函數(shù)做一個開關(guān),當(dāng) GIN_MODE 是 release 模式,就不注入這個 middleware,這樣第 1,2 就不會存在,而是原有的 net/http 框架中 ResponseWriter -- 回答問題 3,4

說到了這么多內(nèi)容,我們來點實際的。

第 1 點代碼怎么寫

type responseBodyWriter struct {
    gin.ResponseWriter  // 繼承原有 gin.ResponseWriter
    bodyBuf *bytes.Buffer  // Body 內(nèi)容臨時存儲位置,這里指針,原因這個存儲對象要復(fù)用
}

// 覆蓋原有 gin.ResponseWriter 中的 Write 方法
func (w *responseBodyWriter) Write(b []byte) (int, error) {
    if count, err := w.bodyBuf.Write(b); err != nil {  // 寫入數(shù)據(jù)時,也寫入一份數(shù)據(jù)到緩存中
        return count, err
    }
    return w.ResponseWriter.Write(b) // 原始框架數(shù)據(jù)寫入
}

第 2 點代碼怎么寫

創(chuàng)建一個 bytes.Buffer 指針 pool

type bodyBuff struct {
    bodyBuf *bytes.Buffer
}

func newBodyBuff() *bodyBuff {
    return &bodyBuff{
        bodyBuf: bytes.NewBuffer(make([]byte, 0, bytesBuff.ConstDefaultBufferSize)),
    }
}

var responseBodyBufferPool = sync.Pool{New: func() interface{} {
    return newBodyBuff()
}}

創(chuàng)建一個 gin middleware,用于從 pool 獲得 bytes.Buffer 指針,并創(chuàng)建 responseBodyWriter 對象覆蓋原有 gin 框架中 Context 中的 ResponseWriter,隨后清理對象回收 bytes.Buffer 指針到 pool 中。

func ginResponseBodyBuffer() gin.HandlerFunc {
    return func(c *gin.Context) {
        var b *bodyBuff
        // 創(chuàng)建緩存對象
        b = responseBodyBufferPool.Get().(*bodyBuff)
        b.bodyBuf.Reset()
        c.Set(responseBodyBufferKey, b)

        // 覆蓋原有 writer
        wr := responseBodyWriter{
            ResponseWriter: c.Writer,
            bodyBuf:        b.bodyBuf,
        }
        c.Writer = &wr

        // 下一個
        c.Next()

        // 歸還緩存對象
        wr.bodyBuf = nil
        if o, ok := c.Get(responseBodyBufferKey); ok {
            b = o.(*bodyBuff)
            b.bodyBuf.Reset()
            responseBodyBufferPool.Put(o)     // 歸還對象
            c.Set(responseBodyBufferKey, nil) // 釋放指向 bodyBuff 對象
        }
    }
}

第 3 點代碼怎么寫

這里最簡單了,寫一個 if 判斷就行了。

func NewEngine(...) *Engine {
    ...

    engine := new(Engine)

    ...

    if gin.IsDebugging() {
        engine.ginSvr.Use(ginResponseBodyBuffer())
    }

    ...
}

看到這里,有的小伙伴就會問了, 你還是沒有說怎么輸出啊,我抄不到作業(yè)呢。也是哦,都說到這里了,感覺現(xiàn)在不給作業(yè)抄,怕是有小伙伴要掀桌子。

作業(yè) 1:日志輸出 middleware 代碼編寫

func GenerateResponseBody(c *gin.Context) string {
    if o, ok := c.Get(responseBodyBufferKey); ok {
        return utils.BytesToString(o.(*bodyBuff).bodyBuf.Bytes())
    } else {
        return "failed to get response body"
    }
}

func ginLogger() gin.HandlerFunc {
    return func(c *gin.Context) {
        // 正常處理系統(tǒng)日志
        path := GenerateRequestPath(c)
        requestBody := GenerateRequestBody(c)

        // 下一個
        c.Next()

        // response 返回
        responseBody := GenerateResponseBody(c)

        // 日志輸出
        log.Println("path: ", path, "requestBody: ", requestBody, "responseBody", responseBody)
    }
}

作業(yè) 2:日志輸出 middleware 安裝

func NewEngine(...) *Engine {
    ...

    engine := new(Engine)

    ...

    if gin.IsDebugging() {
        engine.ginSvr.Use(ginResponseBodyBuffer(), ginLogger())
    }

    ...
}

這里只要把 ginLogger 放在 ginResponseBodyBuffer 這個 middleware 后面就可以了。

測試代碼

Console 內(nèi)容輸出

$ curl -i http://127.0.0.1:8080/xx/
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, AccessToken, X-CSRF-Token, Authorization, Token
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type
Content-Type: application/json; charset=utf-8
X-Request-Id: 1611289702609555456
Date: Fri, 06 Jan 2023 09:12:56 GMT
Content-Length: 14

["lee","demo"]

服務(wù)日志輸出

{"level":"INFO","time":"2023-01-06T17:12:56.074+0800","caller":"server/middleware.go:78","message":"http access log","requestID":"1611289702609555456","status":200,"method":"GET","contentType":"","clientIP":"127.0.0.1","clientEndpoint":"127.0.0.1:62865","path":"/xx/","latency":"280.73μs","userAgent":"curl/7.54.0","requestQuery":"","requestBody":"","responseBody":"[\"lee\",\"demo\"]"}

總結(jié)

我們通過上面代碼的講解和編寫,基本了解了 gin 的 webservice 框架中 response body 讀取的正確方法,以及如何在現(xiàn)有工程中集成現(xiàn)有的功能。 當(dāng)然上面所有的內(nèi)容,僅僅提供了一種解題的可能性,小伙伴應(yīng)該理解思路,結(jié)合自己的應(yīng)用場景,完善和改進代碼。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容