将传入的 HTTP 请求传递到 Go 中的另一个服务器
在迁移服务的上下文中,通常需要将请求转发到不同的版本一个应用程序的。这可以通过复制传入的 HTTP 请求并将其发送到所需的目标来实现。
但是,尝试使用 req.URL.Host 和 req.Host 直接转发原始请求将导致错误“http : 无法在客户端请求中设置Request.RequestURI。”为了克服这个问题,需要一种更全面的方法。
一种有效的方法是利用反向代理的原理,如 net/http/httputil 中的示例。通过创建一个新请求并有选择地复制所需的部分,我们可以有效地转发请求。
这是一个示例实现:
func handler(w http.ResponseWriter, req *http.Request) { // Buffer the request body to preserve its contents body, err := ioutil.ReadAll(req.Body) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } req.Body = ioutil.NopCloser(bytes.NewReader(body)) // Construct the target URL from the original request url := fmt.Sprintf("%s://%s%s", proxyScheme, proxyHost, req.RequestURI) // Create the new request with the modified URL and buffered body proxyReq, err := http.NewRequest(req.Method, url, bytes.NewReader(body)) // Selectively copy relevant headers proxyReq.Header = make(http.Header) for h, val := range req.Header { proxyReq.Header[h] = val } // Execute the request through the HTTP client resp, err := httpClient.Do(proxyReq) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } defer resp.Body.Close() // Forward the response back to the original request }
通过使用这种方法,您可以有效地转发传入的 HTTP请求到多个目的地,以便在服务迁移或其他需要请求重定向的场景中实现平滑过渡。
以上是如何在 Go 中将传入的 HTTP 请求转发到另一台服务器?的详细内容。更多信息请关注PHP中文网其他相关文章!