Home > Backend Development > Golang > How do I Inspect and Modify the Response Body in a Go Reverse Proxy?

How do I Inspect and Modify the Response Body in a Go Reverse Proxy?

Linda Hamilton
Release: 2024-11-07 22:48:02
Original
385 people have browsed it

How do I Inspect and Modify the Response Body in a Go Reverse Proxy?

How to Inspect and Modify Response Body in ReverseProxy

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.

Implementation

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)
}
Copy after login

How It Works

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template