
In the provided Go code, a reverse proxy is set up to redirect requests to Google. However, to gain deeper insights or customize responses, accessing the response body is essential.
The solution lies in leveraging the ModifyResponse field within the ReverseProxy struct. This field allows for specifying a function that modifies the HTTP response before it reaches the client.
The following modified code demonstrates how to read and modify the response body:
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
)
func main() {
target := &url.URL{Scheme: "http", Host: "www.google.com"}
proxy := httputil.NewSingleHostReverseProxy(target)
// Modify the response body before sending it to the client
proxy.ModifyResponse = func(resp *http.Response) (err error) {
b, err := ioutil.ReadAll(resp.Body) // Read the response body
if err != nil {
return err
}
err = resp.Body.Close() // Close the `Body` and `resp`
if err != nil {
return err
}
// Modify the response body
b = bytes.Replace(b, []byte("server"), []byte("schmerver"), -1)
// Create a new `body` to keep the `Content-Length` and `Body` up-to-date
body := ioutil.NopCloser(bytes.NewReader(b))
resp.Body = body
resp.ContentLength = int64(len(b))
resp.Header.Set("Content-Length", strconv.Itoa(len(b)))
fmt.Println("Modified response: ", string(b)) // See the modified response
return nil
}
http.Handle("/google", proxy)
http.ListenAndServe(":8099", nil)
}The ModifyResponse function reads the original response body into a buffer using ioutil.ReadAll. It then closes the original resp.Body and modifies the body content.
To ensure that the response is valid, a new body is created and assigned to resp.Body. The Content-Length header is also updated to reflect the new body length.
Finally, the modified response body is printed to the console for easy inspection, and the modified resp is sent to the client.
The above is the detailed content of How do I Inspect and Modify the Response Body in a Go Reverse Proxy?. For more information, please follow other related articles on the PHP Chinese website!