GO语言”net/http/httputil”包中”ReverseProxy”类型的用法及代码示例。

ReverseProxy 是一个 HTTP 处理程序,它接受传入的请求并将其发送到另一台服务器,将响应代理回客户端。

ReverseProxy 默认将客户端 IP 设置为 X-Forwarded-For 标头的值。

如果 X-Forwarded-For 标头已存在,则客户端 IP 将附加到现有值。作为一种特殊情况,如果标头存在于 Request.Header 映射中但具有 nil 值(例如由 Director func 设置时),则不会修改 X-Forwarded-For 标头。

为防止 IP 欺骗,请务必删除来自客户端或不受信任的代理的任何预先存在的 X-Forwarded-For 标头。

用法:

type ReverseProxy struct {
    // Director must be a function which modifies
    // the request into a new request to be sent
    // using Transport.Its response is then copied
    // back to the original client unmodified.
    // Director must not access the provided Request
    // after returning.
    Director func(*http.Request)

    // The transport used to perform proxy requests.
    // If nil, http.DefaultTransport is used.
    Transport http.RoundTripper

    // FlushInterval specifies the flush interval
    // to flush to the client while copying the
    // response body.
    // If zero, no periodic flushing is done.
    // A negative value means to flush immediately
    // after each write to the client.
    // The FlushInterval is ignored when ReverseProxy
    // recognizes a response as a streaming response, or
    // if its ContentLength is -1; for such responses, writes
    // are flushed to the client immediately.
    FlushInterval time.Duration

    // ErrorLog specifies an optional logger for errors
    // that occur when attempting to proxy the request.
    // If nil, logging is done via the log package's standard logger.
    ErrorLog *log.Logger // Go 1.4

    // BufferPool optionally specifies a buffer pool to
    // get byte slices for use by io.CopyBuffer when
    // copying HTTP response bodies.
    BufferPool BufferPool // Go 1.6

    // ModifyResponse is an optional function that modifies the
    // Response from the backend.It is called if the backend
    // returns a response at all, with any HTTP status code.
    // If the backend is unreachable, the optional ErrorHandler is
    // called without any call to ModifyResponse.
    //
    // If ModifyResponse returns an error, ErrorHandler is called
    // with its error value.If ErrorHandler is nil, its default
    // implementation is used.
    ModifyResponse func(*http.Response) error // Go 1.8

    // ErrorHandler is an optional function that handles errors
    // reaching the backend or errors from ModifyResponse.
    //
    // If nil, the default is to log the provided error and return
    // a 502 Status Bad Gateway response.
    ErrorHandler func(http.ResponseWriter, *http.Request, error) // Go 1.11
}

例子:

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "net/http/httptest"
    "net/http/httputil"
    "net/url"
)

func main() {
    backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "this call was relayed by the reverse proxy")
    }))
    defer backendServer.Close()

    rpURL, err := url.Parse(backendServer.URL)
    if err != nil {
        log.Fatal(err)
    }
    frontendProxy := httptest.NewServer(httputil.NewSingleHostReverseProxy(rpURL))
    defer frontendProxy.Close()

    resp, err := http.Get(frontendProxy.URL)
    if err != nil {
        log.Fatal(err)
    }

    b, err := io.ReadAll(resp.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s", b)

}

输出:

this call was relayed by the reverse proxy