Home >Backend Development >Golang >How Can I Forward Incoming HTTP Requests to Another Server in Go?
Passing Incoming HTTP Requests to Another Server in Go
In the context of migrating services, it is often necessary to forward requests to different versions of an application. This can be achieved by copying the incoming HTTP request and sending it to the desired target.
However, attempts to directly forward the original request using req.URL.Host and req.Host will result in the error "http: Request.RequestURI can't be set in client requests." To overcome this, a more comprehensive approach is required.
One effective method is to utilize the principles of reverse proxying, as exemplified in net/http/httputil. By creating a new request and selectively copying the required parts, we can forward the request effectively.
Here's an example implementation:
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 }
By using this approach, you can efficiently forward incoming HTTP requests to multiple destinations, allowing for smooth transitions during service migrations or other scenarios requiring request redirection.
The above is the detailed content of How Can I Forward Incoming HTTP Requests to Another Server in Go?. For more information, please follow other related articles on the PHP Chinese website!