我正在尝试编写一个中间件,它将拦截http.Fileserver提供的所有文件,并重写HTML文件中的URL。截取写函数可以正常工作,但是当我尝试将修改后的超文本标记语言写回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 i.w.Write([]byte(out))时,应用程序无法按预期工作。根据HTML页面的大小,它要么根本不显示HTML,要么显示长度为32768字节的HTML文件片段。
如果有更好的方法,或者我可能在这个实现中做错了什么,我将非常感谢您的任何提示。
发布于 2021-05-17 05:16:26
我不能让响应拦截中间件方法工作,所以我尝试使用中间代理,如下所示:
启动在localhost:8080上运行的代理基于以下内容:https://gist.github.com/yowu/f7dc34bd4736a65ff28d
network proxy fileserver
:8080 :10000
.---------. .---------. .---------.
<----|- - < - -|---<---|- - < - -|---<---|- < -| |
you ---->|- - > - -|--->---|- -,- > -|--->---|- > -| |
| | | |(*) | | |
website<-|- - < - -|---<---|< -' | | |
| | | | | |
`---------´ `---------´ `---------´
(*) Modify the response from the fileserver to change the target URL它确实解决了问题,但更复杂。如果能知道是否有其他可能更简单的方法,那就太好了。
https://stackoverflow.com/questions/67370582
复制相似问题