In the given Go code, a reverse proxy is set up to redirect requests to www.google.com. While the reverse proxy is functioning correctly, the question arises: how can one access the response body of the proxied request?
The solution to this lies in the httputil package, which provides the ReverseProxy type. In the latest version of the package, ReverseProxy offers an optional ModifyResponse function that enables customization and inspection of the response coming from the backend.
Specifically, by implementing this function, developers can modify the *http.Response before passing it to the client. One potential use case for ModifyResponse is reading and manipulating the response body.
To demonstrate this, consider the following modified code:
package main import ( "bytes" "fmt" "io/ioutil" "net/http" "net/http/httputil" "net/url" ) func main() { target := &url.URL{Scheme: "http", Host: "www.google.com"} proxy := httputil.NewSingleHostReverseProxy(target) proxy.ModifyResponse = func(resp *http.Response) (err error) { b, err := ioutil.ReadAll(resp.Body) // Read the HTML response body if err != nil { return err } resp.Body.Close() // The body is closed by the ReadAll function, but it's good practice to close it again b = bytes.Replace(b, []byte("server"), []byte("schmerver"), -1) // Modify the HTML response by replacing "server" with "schmerver" newBody := ioutil.NopCloser(bytes.NewReader(b)) resp.Body = newBody resp.ContentLength = int64(len(b)) resp.Header.Set("Content-Length", strconv.Itoa(len(b))) fmt.Println(resp) // Print the modified response for debugging purposes return nil } http.Handle("/google", proxy) http.ListenAndServe(":8099", nil) }
In this code, the ModifyResponse function is defined to read the HTML response body, modify it by replacing a particular string, and then set the modified body as the response body. By handling the "/google" URL path, requests to www.google.com will be proxied and the modified response will be sent back to the client.
The above is the detailed content of How to Inspect and Modify the Response Body of a Reverse Proxy in Go?. For more information, please follow other related articles on the PHP Chinese website!