如何使用 NewSingleHostReverseProxy 处理错误

我正在尝试做一个负载均衡器来研究一些 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)

}


繁花如伊
浏览 129回答 2
2回答

跃然一笑

当我最终在这里寻找一种处理来自代理主机的 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)}  

交互式爱情

使用 proxy.ErrorHandlerErrorHandler 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)    }     
打开App,查看更多内容
随时随地看视频慕课网APP