Home > Backend Development > Golang > How can I access the response body in Go's reverse proxy?

How can I access the response body in Go's reverse proxy?

Patricia Arquette
Release: 2024-11-19 16:39:02
Original
609 people have browsed it

How can I access the response body in Go's reverse proxy?

How to Access Response Body in Go's Reverse Proxy

In Go, the httputil/reverseproxy package provides a convenient way to implement a reverse proxy server. However, accessing the response body of the underlying HTTP request can be challenging.

Original Code

The given Go code demonstrates a simple reverse proxy server:

package main

import (
    "net/http"
    "net/http/httputil"
    "net/url"
)

func main() {
    target := &url.URL{Scheme: "http", Host: "www.google.com"}
    proxy := httputil.NewSingleHostReverseProxy(target)

    http.Handle("/google", proxy)
    http.ListenAndServe(":8099", nil)
}
Copy after login

Accessing Response Body

To access the response body, you can utilize the ModifyResponse function provided by the httputil/reverseproxy package. This function allows you to modify the HTTP response before it is sent to the client.

By implementing the ModifyResponse function, you can perform various operations on the response, including:

  • Read and modify the response body
  • Set custom headers
  • Redirect the response

Example

Here's an example of how you can modify the response body:

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
}

target, _ := url.Parse("http://example.com")
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.ModifyResponse = rewriteBody
Copy after login

By implementing the ModifyResponse function in this way, you can modify and read the response body before it is sent to the client.

The above is the detailed content of How can I access the response body in Go's 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