dongzhi6463 2019-07-12 01:05
浏览 390
已采纳

如何使用NewSingleHostReverseProxy处理错误

I'm trying to do a load balancer to study some go packages.

I want to handle errors when the request timeout or give 404 error but can't find how to do that.

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)

}

  • 写回答

1条回答 默认 最新

  • douye2110 2019-07-12 02:24
    关注

    use proxy.ErrorHandler

    ErrorHandler func(http.ResponseWriter, *http.Request, error)

      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)
        }     
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程