我想問一下,我們是否可以爲Go http客戶端創建'中間件'功能?示例我想添加一個日誌函數,因此每個發送的請求都會被記錄下來,或者添加setAuthToken,以便將令牌添加到每個請求的標題中。Go http客戶端是否有'中間件'?
2
A
回答
5
您可以使用HTTP客戶端Transport
參數到效果,與構圖模式,使用的事實是:
http.Client.Transport
定義了處理所有HTTP請求的函數;http.Client.Transport
具有接口類型http.RoundTripper
,因此可以用您自己的實現來替換;
例如:
package main
import (
"fmt"
"net/http"
)
// This type implements the http.RoundTripper interface
type LoggingRoundTripper struct {
Proxied http.RoundTripper
}
func (lrt LoggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, e error) {
// Do "before sending requests" actions here.
fmt.Printf("Sending request to %v\n", req.URL)
// Send the request, get the response (or the error)
res, e = lrt.Proxied.RoundTrip(req)
// Handle the result.
if (e != nil) {
fmt.Printf("Error: %v", e)
} else {
fmt.Printf("Received %v response\n", res.Status)
}
return
}
func main() {
var c = &http.Client{Transport:LoggingRoundTripper{http.DefaultTransport}}
c.Get("https://www.google.com")
}
隨意更改名稱,你想,我沒想到他們很長時間。
0
這可以通過使用閉包函數來實現。這也可能是用一個例子更加清晰:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/hello", logged(hello))
http.ListenAndServe(":3000", nil)
}
func logged(f func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Println("logging something")
f(w, r)
fmt.Println("finished handling request")
}
}
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "<h1>Hello!</h1>")
}
歸功於:http://www.calhoun.io/5-useful-ways-to-use-closures-in-go/
相關問題
- 1. 告訴HTTP客戶端是否斷開
- 2. 是否有任何HTTP客戶端支持Socket.outputProgress上傳?
- 3. 是否有適用於Windows的HTTP Live Streaming客戶端?
- 4. 是否有Java(Android)的HTTP客戶端類?
- 5. 中的Apache HTTP客戶端
- 6. 在HTTP客戶端
- 7. apache http客戶端
- 8. 是否有客戶端JavaScript mimetype庫?
- 9. 是否有Erlang BERT-RPC客戶端?
- 10. Oauth2是否有任何Php客戶端?
- 11. 是否有Expression Blend的SVN客戶端?
- 12. 是否有Kafka Connect Python客戶端?
- 13. 是否有Python ebXML客戶端?
- 14. Mondrian是否有本地客戶端?
- 15. 是否有PouchDB的GUI客戶端?
- 16. 禁用通用名稱驗證 - Go HTTP客戶端
- 17. 從客戶端發送文件到客戶端通過HTTP
- 18. 還有沒有HTTP/1.0客戶端?
- 19. 在Go中的客戶端和服務器之間的通信
- 20. 是否有支持iOS的Delphi的HTTP客戶端/服務器組件?
- 21. 是請求(HTTP請求客戶端)是否同步?
- 22. Akka HTTP客戶端akka-http akka-http-jackson
- 23. 使用Go Redis客戶端(Redigo)
- 24. nsq go客戶端無法跟上
- 25. HTTP客戶端類中的單例模式是否會導致競爭條件?
- 26. 在客戶端結構中包含HTTP請求的HTTP客戶端
- 27. Go中的UDP服務器/客戶端沒有讀取數據
- 28. 是否可以更改HTTP客戶端超時期限(cpp-netlib)?
- 29. 檢查客戶端是否收到http響應
- 30. 是否可以使用Dart http庫添加客戶端憑證?
謝謝。但是,當我們發送請求 – quangpn88
時,我想要的對於http客戶端來說也是一樣的。這並沒有回答這個問題 - 它是在服務HTTP時執行中間件的一種方式,而不是在請求它時。 –
糟糕,我沒有花時間理解你的問題。對於客戶端來說,類似的東西絕對是可能的。我會看看我是否可以在當天晚些時候舉一個例子:) – Bugless