draxq02664 2018-04-10 04:20
浏览 239
已采纳

ReverseProxy取决于请求.golang中的主体

I want to build a http reverse proxy which checks the HTTP body and send HTTP requests to it's upstream servers after that. How can you do that in go?

Initial attempt (follows) fails because ReverseProxy copies the incoming request, modifies it and sends but the body is already read.

func main() {
    backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        b, err := ioutil.ReadAll(r.Body)
        if err != nil {
            http.Error(w, fmt.Sprintf("ioutil.ReadAll: %s", err), 500)
            return
        }
        // expecting to see hoge=fuga
        fmt.Fprintf(w, "this call was relayed by the reverse proxy, body: %s", string(b))
    }))
    defer backendServer.Close()

    rpURL, err := url.Parse(backendServer.URL)
    if err != nil {
        log.Fatal(err)
    }

    proxy := func(u *url.URL) http.Handler {
        p := httputil.NewSingleHostReverseProxy(u)
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            if err := r.ParseForm(); err != nil {
                http.Error(w, fmt.Sprintf("ParseForm: %s", err), 500)
                return
            }
            p.ServeHTTP(w, r)
        })
    }(rpURL)
    frontendProxy := httptest.NewServer(proxy)
    defer frontendProxy.Close()

    resp, err := http.Post(frontendProxy.URL, "application/x-www-form-urlencoded", bytes.NewBufferString("hoge=fuga"))
    if err != nil {
        log.Fatalf("http.Post: %s", err)
    }

    b, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatalf("ioutil.ReadAll: %s", err)
    }

    fmt.Printf("%s", b)
}
// shows: "http: proxy error: http: ContentLength=9 with Body length 0"

Then my next attempt would be to read the whole body into bytes.Reader and use that to check the body content, and Seek to the beginning before sending to upstream servers. But then I have to re-implement ReverseProxy which I would like to avoid. Is there any other elegant way?

  • 写回答

2条回答 默认 最新

  • duan4523 2018-04-10 06:31
    关注

    edit:

    As commented above, the parsed form will be empty in this case. You will need to manually parse the form from the body.

    The request.Body is a io.ReaderCloser, because this describes the rx part of a tcp connection. But in your use case you need to read everything since you are parsing the body into a form. The trick here is to reassign the r.Body with a io.ReaderCloser object derived from the already read data. Here is what I would do:

    1. Get a reference of the request body as a byte slice:

      // before calling r.ParseForm(), get the body
      // as a byte slice
      body, err := ioutil.ReadAll(r.Body)
    

    2. Reassign r.Body after parsing form

      // after calling r.ParseForm(), reassign body
      r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
    

    bytes.NewBuffer(body) converts the body byte slice into a io.Reader, and ioutil.NopCloser convertts a io.Reader into a io.ReaderCloser with a nop Close() method.

    Putting Everything Together

      package main
    
      import "net/http"
      import "net/http/httputil"
      import "net/url"
      import "net/http/httptest"
      import "fmt"
      import "log"
      import "bytes"
      import "io/ioutil"
    
      func main() {
        backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            b, err := ioutil.ReadAll(r.Body)
            if err != nil {
                http.Error(w, fmt.Sprintf("ioutil.ReadAll: %s", err), 500)
                return
            }
            // expecting to see hoge=fuga
            fmt.Fprintf(w, "this call was relayed by the reverse proxy, body: %s", string(b))
        }))
        defer backendServer.Close()
    
        rpURL, err := url.Parse(backendServer.URL)
        if err != nil {
            log.Fatal(err)
        }
    
        proxy := func(u *url.URL) http.Handler {
            p := httputil.NewSingleHostReverseProxy(u)
            return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                // read out body into a slice
                body, err := ioutil.ReadAll(r.Body)
                if err != nil {
                    http.Error(w, fmt.Sprintf("Error reading body: %s", err), 500)
                    return
                }
    
                // inspect current body here
                if err := r.ParseForm(); err != nil {
                    http.Error(w, fmt.Sprintf("ParseForm: %s", err), 500)
                    return
                }
    
                // assign a new body with previous byte slice
                r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
                p.ServeHTTP(w, r)
            })
        }(rpURL)
        frontendProxy := httptest.NewServer(proxy)
        defer frontendProxy.Close()
    
        resp, err := http.Post(
            frontendProxy.URL,
            "application/x-www-form-urlencoded",
            bytes.NewBufferString("hoge=fuga"))
        if err != nil {
            log.Fatalf("http.Post: %s", err)
        }
    
        b, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            log.Fatalf("ioutil.ReadAll: %s", err)
        }
    
        fmt.Printf("%s", b)
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配