dta38159 2018-07-16 06:52
浏览 405
已采纳

如何使用proxy.ModifyResponse?

I've implemented the most basic Reverse Proxy to pull a page and then add some content to the body. Unfortunately my attempt to add to the html isn't taking effect. The code below just shows the original page but without the "monkeys" I prepended to the response. What additional calls are needed to get this to work? I eventually want to use this to replace css for custom css.

package main

import (
    "log"
    "net/http"
    "net/http/httputil"
    "net/url"
    "fmt"
    "github.com/PuerkitoBio/goquery"
    "bytes"
)

type Director func(*http.Request)

func (f Director) Then(g Director) Director {
    return func(req *http.Request) {
        f(req)
        g(req)
    }
}

func hostDirector(host string) Director {
    return func(req *http.Request) {
        req.Host = host
    }
}

func UpdateResponse(r *http.Response) error {
    doc, err := goquery.NewDocumentFromReader(r.Body)
    if err != nil{
        //log.New("Research")
        log.Fatal("Bad doc %v", err)
        return err
    }
    html, err := goquery.OuterHtml(doc.First())
    if err != nil{
        log.Fatal("Bad html %v", err)
        return err
    }
    fmt.Printf("Body %v", html)
    r.Write(bytes.NewBufferString("monkeys"+html))

    return nil
}

func main() {
    url, _ := url.Parse("http://cnn.com/")
    proxy := httputil.NewSingleHostReverseProxy(url)

    d := proxy.Director
    // sequence the default director with our host director
    proxy.Director = Director(d).Then(hostDirector(url.Hostname()))
    proxy.ModifyResponse = UpdateResponse
    http.Handle("/", proxy)
    log.Fatal(http.ListenAndServe(":9090", nil))
}
  • 写回答

1条回答 默认 最新

  • dongwu9972 2018-07-16 18:04
    关注

    Your ModifyResponse code is not modifying the response. In your code, you have:

    r.Write(bytes.NewBufferString("monkeys"+html))
    

    It seems that you are writing to the response, but nope. r is of *http.Response which has a Write method:

    func (r *Response) Write(w io.Writer) error
    

    The document says:

    Write writes r to w in the HTTP/1.x server response format, including the status line, headers, body, and optional trailer.

    Since bytes.Buffer also implements a io.Writer, the code compiles, but instead of write to the response from the buffer, it write the response to the buffer, which is absolutely undesired.

    The fact is, http.Response simply don't provide a way to modify its Body. It is clear that Bodey is an io.ReadCloser. What you can do is create a new io.ReadCloser with the body. Remember to change Content-Length field in the Header or it may cause problem.

    func UpdateResponse(r *http.Response) error {
        b, _ := ioutil.ReadAll(r.Body)
        buf := bytes.NewBufferString("Monkey")
        buf.Write(b)
        r.Body = ioutil.NopCloser(buf)
        r.Header["Content-Length"] = []string{fmt.Sprint(buf.Len())}
        return nil
    }
    

    Playground: https://play.golang.org/p/_Tyvo6GVN3x

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵