gpt4 book ai didi

http - 如何使用 NewSingleHostReverseProxy 处理错误

转载 作者:数据小太阳 更新时间:2023-10-29 03:18:54 31 4
gpt4 key购买 nike

我正在尝试做一个负载均衡器来研究一些 go 包。

我想在请求超时或出现 404 错误时处理错误,但找不到如何处理。

func main() {
// start server
http.HandleFunc("/", handleRequestAndRedirect)

if err := http.ListenAndServe(getListenAddress(), nil); err != nil {
panic(err)
}
}

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.ServeHTTP(res, req)

最佳答案

当我最终来到这里寻找一种方法来处理来自代理主机的 404 错误时,我想补充已接受的答案,如果它对登陆此页面的人有任何帮助的话。

如官方文档 ( https://golang.org/pkg/net/http/httputil/#ReverseProxy ) 中所述:

ModifyResponse is an optional function that modifies the Response from the backend. It is called if the backend returns a response at all, with any HTTP status code.If the backend is unreachable, the optional ErrorHandler is called without any call to ModifyResponse. If ModifyResponse returns an error, ErrorHandler is called with its error value. If ErrorHandler is nil, its default implementation is used.

因此,如果您不仅要捕获“真正的”错误(主机无法访问),还要捕获来自服务器的错误响应代码(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)
}

关于http - 如何使用 NewSingleHostReverseProxy 处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56999012/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com