Golang中Exchange调用提供的代码不应通过代理服务器传输

Golang中Exchange调用提供的代码不应通过代理服务器传输 大家好,

请审阅以下代码。交换调用所提供的代码绝不应经过代理服务器。

func proxyHandler(c *gin.Context) {
	remote, err := url.Parse("office365 URL")
	if err != nil {
		// Handle error
		c.AbortWithError(http.StatusInternalServerError, err)
		return
	}
	proxy := httputil.NewSingleHostReverseProxy(remote)
	proxy.Director = func(req *http.Request) {
		req.Header = c.Request.Header
		req.Header.Set("Authorization", "Token")
		req.Host = remote.Host
		req.URL.Scheme = remote.Scheme
		req.URL.Host = remote.Host
		req.URL.Path = c.Param("proxyPath")
	}
	proxy.ServeHTTP(c.Writer, c.Request)
}

请大家帮忙建议一下,我上面的代码哪里出错了。


更多关于Golang中Exchange调用提供的代码不应通过代理服务器传输的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中Exchange调用提供的代码不应通过代理服务器传输的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang中,确保HTTP请求不经过代理服务器的标准做法是使用自定义的http.Transport,并设置其Proxy字段为nil。在您的代码中,httputil.NewSingleHostReverseProxy创建的代理默认会使用环境变量中的代理设置。要绕过代理,您需要为反向代理指定一个自定义的Transport

以下是修改后的代码示例:

func proxyHandler(c *gin.Context) {
    remote, err := url.Parse("office365 URL")
    if err != nil {
        c.AbortWithError(http.StatusInternalServerError, err)
        return
    }
    
    proxy := httputil.NewSingleHostReverseProxy(remote)
    // 创建自定义Transport,禁用代理
    proxy.Transport = &http.Transport{
        Proxy: nil, // 设置为nil以禁用代理
    }
    
    proxy.Director = func(req *http.Request) {
        req.Header = c.Request.Header
        req.Header.Set("Authorization", "Token")
        req.Host = remote.Host
        req.URL.Scheme = remote.Scheme
        req.URL.Host = remote.Host
        req.URL.Path = c.Param("proxyPath")
    }
    proxy.ServeHTTP(c.Writer, c.Request)
}

通过将proxy.TransportProxy字段设置为nil,HTTP请求将直接连接到目标服务器,而不会经过任何代理服务器。这确保了Exchange调用提供的代码不会通过代理传输。

回到顶部