2 回答

TA貢獻1826條經驗 獲得超6個贊
當我最終在這里尋找一種處理來自代理主機的 404 錯誤的方法時,我想補充已接受的答案,如果它對登陸此頁面的人有任何幫助的話。
正如官方文檔(https://golang.org/pkg/net/http/httputil/#ReverseProxy)中所述:
ModifyResponse 是一個可選函數,用于修改來自后端的 Response。如果后端返回帶有任何 HTTP 狀態代碼的響應,則會調用它。如果后端無法訪問,則調用可選的ErrorHandler,而不調用任何ModifyResponse。如果ModifyResponse返回錯誤,則使用其錯誤值調用ErrorHandler。如果 ErrorHandler 為 nil,則使用其默認實現。
因此,如果您不僅想捕獲“真實”錯誤(主機無法訪問),還想捕獲來自服務器的錯誤響應代碼(404、500...),您應該使用檢查響應狀態代碼并返回錯誤,這將ModifyResponse
是然后被你的ErrorHandler
函數捕獲。接受的答案示例變為:
func handleRequestAndRedirect(res http.ResponseWriter, req *http.Request) {
ur, _ := url.Parse("https://www.instagram.com/")
proxy := httputil.NewSingleHostReverseProxy(ur)
// Update the headers to allow for SSL redirection
req.URL.Host = ur.Host
req.URL.Scheme = ur.Scheme
req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
req.Host = ur.Host
req.Header.Set("Key", "Teste")
proxy.ErrorHandler = ErrHandle
proxy.ModifyResponse = ModifyResponse
proxy.ServeHTTP(res, req)
}
func ModifyResponse(res *http.Response) error {
if res.StatusCode == 404 {
return errors.New("404 error from the host")
}
return nil
}
func ErrHandle(res http.ResponseWriter, req *http.Request, err error) {
fmt.Println(err)
}

TA貢獻1712條經驗 獲得超3個贊
使用 proxy.ErrorHandler
ErrorHandler func(http.ResponseWriter, *http.Request, 錯誤)
func handleRequestAndRedirect(res http.ResponseWriter, req *http.Request) {
ur, _ := url.Parse("https://www.instagram.com/")
proxy := httputil.NewSingleHostReverseProxy(ur)
// Update the headers to allow for SSL redirection
req.URL.Host = ur.Host
req.URL.Scheme = ur.Scheme
req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
req.Host = ur.Host
req.Header.Set("Key", "Teste")
proxy.ErrorHandler = ErrHandle
proxy.ServeHTTP(res, req)
}
func ErrHandle(res http.ResponseWriter, req *http.Request, err error) {
fmt.Println(err)
}
- 2 回答
- 0 關注
- 212 瀏覽
添加回答
舉報