登录
首页 >  Golang >  Go问答

每个主机的 Golang ReverseProxy

来源:stackoverflow

时间:2024-04-06 19:21:36 465浏览 收藏

本篇文章向大家介绍《每个主机的 Golang ReverseProxy》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

我正在尝试在 go 中实现反向代理,该代理根据 url 中嵌入的某些租户将流量代理到不同的主机。实现如下所示:

type offloader struct {
    tenanthostmap   map[string]string                   // map a tenant to its host:port
    tenantproxymap  map[string](*httputil.reverseproxy) // map a tenant to its reverse proxy
}

func (o *offloader) oncreate() {

    // tenants map
    o.tenanthostmap = make(map[string]string)
    o.tenantproxymap = make(map[string]*httputil.reverseproxy)
    o.populatetenanthostmap()

    // rx
    http.handlefunc("/", o.servehttp)
    go http.listenandserve(":5555", nil)

}

// servehttp is the callback that is called each time a http request is received.
func (o *offloader) servehttp(w http.responsewriter, req *http.request) {
    incomingurl := req.url.requesturi()
    tenant := o.gettenantfromurl(incomingurl)

    if proxy, ok := o.tenantproxymap[tenant]; ok {
        proxy.servehttp(w, req)
    }

    if remotehostaddr, ok := o.tenanthostmap[tenant]; ok {
        remoteurl, err := url.parse(fmt.sprintf("http://%s", remotehostaddr))
        if err != nil {
            return
        }
        proxy := httputil.newsinglehostreverseproxy(remoteurl)
        o.tenantproxymap[tenant] = proxy
        proxy.servehttp(w, req) // non blocking

    } else {
        panic("unknown tenant")
    }
}

当收到新的 http 请求时,我从 url 获取租户。如果这是我第一次看到这个租户,我会创建一个新的 reverseproxy,否则我会尝试使用之前创建并存储在 tenantproxymap 中的 reverseproxy。

当我测试这个时,我收到以下错误:

2022/04/05 12:31:01 http: proxy error: readfrom tcp ****: http: invalid Read on closed Body
2022/04/05 12:31:01 http: superfluous response.WriteHeader call from net/http/httputil.(*ReverseProxy).defaultErrorHandler (reverseproxy.go:190)

如果我为每个请求创建一个新的反向代理而不是重复使用相同的代理,则不会发生错误。

我认为代理是每个主机而不是每个请求(顾名思义),所以我想知道为什么会发生这个错误?

我知道我需要保护映射免受并发读/写的影响,但这目前无关紧要。

谢谢


正确答案


问题是,在以前的代理已经存在的情况下,您首先将请求传递给该代理 - 然后仍然重新创建代理,并再次传递请求。换句话说:当已经为该租户填充了 tentantproxymap 时,您将为每个传入请求发出两个代理请求。

reverseproxy 实现会关闭 req.body,因此第二次将请求传递到代理时,它会尝试从已关闭的正文中读取。结果,您会看到 http: invalid read on closed body 错误。

您应该尝试的是在代理请求后返回,例如通过添加 return

if proxy, ok := o.tenantProxyMap[tenant]; ok {
    proxy.ServeHTTP(w, req)
    return
}

理论要掌握,实操不能落!以上关于《每个主机的 Golang ReverseProxy》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>