首頁  >  文章  >  後端開發  >  如何使用中介軟體連結和功能處理程序組合器在 Go 的「http.HandleFunc」中記錄 HTTP 回應?

如何使用中介軟體連結和功能處理程序組合器在 Go 的「http.HandleFunc」中記錄 HTTP 回應?

Patricia Arquette
Patricia Arquette原創
2024-10-28 04:41:30783瀏覽

How can you log HTTP responses in Go's `http.HandleFunc` using middleware chaining and functional handler combinators?

在http.HandleFunc

中記錄傳入HTTP 請求的回應

在上一篇標題為「在go 中,如何檢查HTTP寫入http.ResponseWriter 的回應?但是,這種方法可能不適合實時伺服器。

中間件鏈接

另一種解決方案是中間件鏈接,這是一種修改和記錄HTTP 的常用技術響應和請求,同時保留原始的請求-響應流程。

函數處理程序組合器

我們可以建立自己的函數處理程序,而不是使用negroni 這樣的函式庫組合器:

<code class="go">func NewFooHandler(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // do something before
        next(w, r)
        // do something after
    }
}</code>

建立處理程序鏈

我們可以使用組合器將多個處理程序連結在一起:

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

In在本例中,Sink 是一個不執行任何操作的空處理程序。

實作回應日誌記錄

使用處理程序組合器方法,我們可以建立一個記錄回應的處理程序:

<code class="go">func NewResponseLoggingHandler(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Replace the response writer with a recorder
        c := httptest.NewRecorder()
        next(c, r)

        // Copy the response from the recorder to the actual writer
        for k, v := range c.HeaderMap {
            w.Header()[k] = v
        }
        w.WriteHeader(c.Code)
        c.Body.WriteTo(w)
    }
}</code>

應用回應日誌記錄處理程序

我們可以透過建立預設處理程序組合器將回應日誌記錄處理程序套用至所有HTTP 路由:

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

這樣,每當我們啟動像這樣的鏈時:

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

它將自動包含回應日誌記錄和任何其他預設處理程序。

以上是如何使用中介軟體連結和功能處理程序組合器在 Go 的「http.HandleFunc」中記錄 HTTP 回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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