Home > Backend Development > Golang > How to Access the Response Body in a Go Reverse Proxy?

How to Access the Response Body in a Go Reverse Proxy?

Mary-Kate Olsen
Release: 2024-11-08 08:20:02
Original
988 people have browsed it

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

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

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!

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