Home > Backend Development > Golang > How to Access and Modify Response Body in an HTTPutil Reverse Proxy?

How to Access and Modify Response Body in an HTTPutil Reverse Proxy?

Barbara Streisand
Release: 2024-11-12 14:49:02
Original
947 people have browsed it

How to Access and Modify Response Body in an HTTPutil Reverse Proxy?

Accessing Response Body in Reverse Proxy with HTTPutil

HTTPutil provides a powerful reverse proxy implementation in Go. However, it lacks native functionality to access the response body. This article explores a solution for retrieving the response body and modifying it using the ModifyResponse field in the ReverseProxy struct.

HTTPutil Reverse Proxy Overview

In the provided code snippet, a reverse proxy is created using httputil.NewSingleHostReverseProxy. This proxy forwards requests to the target URL, www.google.com. The request is handled at the /google endpoint and listens on port 8099.

Retrieve and Modify Response Body

To access and modify the response body, we utilize the ModifyResponse field in the ReverseProxy struct. This field accepts a function that takes a *http.Response pointer as an argument and returns an error. Within this function, we can read the response body using ioutil.ReadAll, close the existing body, modify the body content, and set the modified body back into the response. The following code demonstrates this:

func rewriteBody(resp *http.Response) (err error) {
    b, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return  err
    }
    err = resp.Body.Close()
    if err != nil {
        return err
    }
    b = bytes.Replace(b, []byte("server"), []byte("schmerver"), -1)
    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
}
Copy after login

In this code, we read the response body, replace specific content in the body, and update the body and headers accordingly. By assigning this function to the ModifyResponse field, we can intercept and manipulate the response body before it is sent to the client.

The above is the detailed content of How to Access and Modify Response Body in an HTTPutil 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