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

如何使用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条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 使用DWY100k数据集对UEA进行测试,出现报错:IndexError: index 125000 is out of bounds for axis 0 with size 95500
      • ¥15 前端vue实现根据图片url生成pdf文件
      • ¥15 RfidReader资源Q个
      • ¥20 user-agent是否是唯一的,有没有可能相同
      • ¥15 关于#开会#的问题,如何解决?(语言-c++)
      • ¥15 关于#二十四点问题#的问题
      • ¥15 运行kitex的demon出错(求大家解决)
      • ¥15 开发一个类似 typora 这样的软件需要多少钱?
      • ¥15 clearcase7.0安装包
      • ¥15 断点回归模型月度核密度检验不连续