2 回答

TA貢獻1757條經驗 獲得超7個贊
您可以簡單地包裝您的HandleFunc,在包裝的處理程序返回后,您可以將更多數據寫入ResponseWriter:
func myhandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello"))
}
func wrapper(w http.ResponseWriter, r *http.Request) {
myhandler(w, r) // Call original
w.Write([]byte(" World")) // Write further data to output
}
func main() {
http.HandleFunc("/", wrapper)
http.ListenAndServe("", nil)
}
訪問任何 URL 將導致響應:
Hello World
生產環境注意事項:
包裝器還應該檢查包裝處理程序的響應代碼或成功,并采取行動(例如,如果提供了錯誤頁面,則可能不希望仍然執行額外的寫入)。
如果
"Content-length"
頭是由包裝處理程序設置的,寫入更多數據將使其無效(因為內容將大于頭中指示的內容)。
針對這種情況的一種可能的“保護”可能是傳遞一個自定義ResponseWriter
實現,該實現僅寫入緩沖區(例如bytes.Buffer
),包裝器將附加到此并"Content-length"
根據新長度進行設置,然后將緩沖區的內容寫入“真實“ 輸出。

TA貢獻1744條經驗 獲得超4個贊
你可以創建自己的http.ResponseWriter來做到這一點,或者你可以只使用“中間件模式”:
// foo is the main handler
type foo struct{}
func (foo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("foo"))
}
// bar writes after foo
type bar struct {
h http.Handler
}
func (b bar) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b.h.ServeHTTP(w, r)
w.Write([]byte("BAR"))
}
游樂場:http : //play.golang.org/p/fB2OXNSTIe。
- 2 回答
- 0 關注
- 217 瀏覽
添加回答
舉報