Home > Article > Backend Development > How to Access the Response Body in a Go Reverse Proxy?
Accessing Response Body in Reverse Proxy
When working with Reverse Proxy, you may encounter the need to access the response body received from the backend server. This article delves into how to retrieve the response body in Go using the httputil package.
In the provided code snippet, you have a simple reverse proxy that forwards requests to Google:
target := &url.URL{Scheme: "http", Host: "www.google.com"} proxy := httputil.NewSingleHostReverseProxy(target) http.Handle("/google", proxy) http.ListenAndServe(":8099", nil)
The key to accessing the response body lies in the ModifyResponse field of the ReverseProxy type. As per the official documentation, ModifyResponse is an optional function that allows you to modify the response from the backend.
Here's an example that reads and modifies the response body before sending it to the client:
import ( "bytes" "fmt" "io/ioutil" ) func rewriteBody(resp *http.Response) (err error) { b, err := ioutil.ReadAll(resp.Body) //Read html if err != nil { return err } err = resp.Body.Close() if err != nil { return err } b = bytes.Replace(b, []byte("server"), []byte("schmerver"), -1) // replace html body := ioutil.NopCloser(bytes.NewReader(b)) resp.Body = body resp.ContentLength = int64(len(b)) resp.Header.Set("Content-Length", strconv.Itoa(len(b))) return nil } func main() { target, _ := url.Parse("http://example.com") proxy := httputil.NewSingleHostReverseProxy(target) proxy.ModifyResponse = rewriteBody http.Handle("/google", proxy) http.ListenAndServe(":8099", nil) }
In this code, the rewriteBody function reads the response body, modifies it (in this case, replacing the word "server" with "schmerver"), and then sets the modified body as the new response body.
The above is the detailed content of How to Access the Response Body in a Go Reverse Proxy?. For more information, please follow other related articles on the PHP Chinese website!