將傳入的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中文網其他相關文章!