首頁  >  文章  >  後端開發  >  如何使用「http.HandleFunc」和中間件記錄即時 HTTP 回應?

如何使用「http.HandleFunc」和中間件記錄即時 HTTP 回應?

DDD
DDD原創
2024-10-27 10:29:03237瀏覽

How to Log Real-Time HTTP Responses with `http.HandleFunc` and Middleware?

使用http.HandleFunc 記錄傳入的HTTP 請求

在先前的討論中,我們探索了使用虛假請求檢查HTTP 回應,這是適合單元測試的技術。然而,我們也尋求一種在即時伺服器上記錄即時回應資料的方法。

中間件鏈

一種流行的方法涉及建立中間件鏈。像 Negroni 這樣的庫提供中間件功能,其中處理程序被組合併按順序執行。使用處理程序組合器可以實現最小中間件實作:

<code class="go">func NewFooHandler(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Do pre-handling tasks
        next(w, r)
        // Do post-handling tasks
    }
}</code>

然後可以將這些組合器連結起來形成處理程序:

<code class="go">h := NewFooHandler(NewBarHandler(NewBazHandler(Sink)))</code>

應用於HTTP.HandleFunc

要將此技術應用於您的問題,您可以建立處理程序組合器:

<code class="go">func NewResponseLoggingHandler(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Record the response
        c := httptest.NewRecorder()
        next(c, r)
        
        // Copy responses
        for k, v := range c.HeaderMap {
            w.Header()[k] = v
        }
        w.WriteHeader(c.Code)
        c.Body.WriteTo(w)
    }
}</code>

現在,您可以建立一個將自訂處理程序與回應日誌記錄結合的默認處理程序:

<code class="go">func NewDefaultHandler(next http.HandlerFunc) http.HandlerFunc {
    return NewResponseLoggingHandler(NewOtherStuffHandler(next))
}</code>

透過使用此預設處理程序:

<code class="go">h := NewDefaultHandler(...)</code>

所有後續處理程序將自動包含回應日誌記錄。

以上是如何使用「http.HandleFunc」和中間件記錄即時 HTTP 回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn