繁体   English   中英

HTTP 文件服务器响应拦截与 URL 重写

[英]HTTP Fileserver Response Intercept with URL rewrite

我正在尝试编写一个中间件,它将拦截http.Fileserver提供的所有文件,并在 HTML 文件中重写 URL。 拦截 Write function 可以正常工作,但是当我尝试将修改后的 HTML 写回 http.ResponseWriter 时,它无法正常工作。

完整的示例代码可以在这里找到: https://gist.github.com/bradstimpson/c2b955122866d68e585c21cb1078aded

在此处复制正常工作的响应拦截器:

type ResponseInterceptor interface {
    Write([]byte) (int, error)
}

type interceptor struct {
    w http.ResponseWriter
    o url.URL
    t url.URL
}

func NewResponseInterceptor(wri http.ResponseWriter, orig url.URL, targ url.URL) http.ResponseWriter {
    return &interceptor{w: wri, o: orig, t: targ}
}

func (i *interceptor) Header() http.Header { return i.w.Header() }

func (i *interceptor) WriteHeader(statusCode int) { i.w.WriteHeader(statusCode) }

func (i *interceptor) Write(b []byte) (int, error) {
    out := strings.ReplaceAll(string(b), i.o.Host, i.t.Host)
    fmt.Println(out)
    return i.w.Write(b)
}

func InterceptMiddleware(o url.URL, t url.URL) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        fn := func(w http.ResponseWriter, r *http.Request) {
            wrapped := NewResponseInterceptor(w, o, t)
            next.ServeHTTP(wrapped, r)
        }

        return http.HandlerFunc(fn)
    }
}

当我将func (i *interceptor) Write(b []byte) (int,error)的返回更改为return iwWrite([]byte(out))时,应用程序无法按预期工作。 根据 HTML 页面的大小,它要么根本不显示 HTML,要么显示长度为 32768 字节的 HTML 文件的片段。

如果有更好的方法,或者我在这个实现中可能做错了什么,我将不胜感激。

我无法让响应拦截中间件方法工作,所以我尝试使用如下中间代理:

  1. 基于此启动在 localhost:8080 上运行的代理: https://gist.github.com/yowu/f7dc34bd4736a65ff28d
  2. 启动在 localhost:10000 上运行的文件服务器
  3. 配置我的 web 浏览器以使用在 localhost:8080 运行的代理
  4. yowu's gist 第 74 行的响应我为目标 URL 做了一个 replaceAll
           network            proxy           fileserver
                              :8080            :10000
         .---------.       .---------.       .---------.
    <----|- - < - -|---<---|- - < - -|---<---|- < -|   |
you ---->|- - > - -|--->---|- -,- > -|--->---|- > -|   |
         |         |       |   |(*)  |       |         |
website<-|- - < - -|---<---|< -'     |       |         |
         |         |       |         |       |         |
         `---------´       `---------´       `---------´

(*) Modify the response from the fileserver to change the target URL

它确实解决了问题,但更复杂。 很高兴知道是否有任何其他可能更简单的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM