HTTP 文件服务器响应拦截与 URL 重写
时间:2024-04-10
浏览:309
作者:佚名
小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《HTTP 文件服务器响应拦截与 URL 重写》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!
我正在尝试编写一个中间件,它将拦截 http.fileserver 提供的所有文件,并重写 html 文件中的 url。拦截 write 函数工作正常,但是当我尝试将修改后的 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 i.w.write([]byte(out)) 时,应用程序无法按预期工作。根据 html 页面的大小,它要么根本不显示 html,要么显示长度为 32768 字节的 html 文件片段。
如果有更好的方法,或者我在这个实现中可能做错了什么,我将非常感谢您提供的任何提示。
正确答案
我无法让响应拦截中间件方法发挥作用,因此我尝试使用中间代理,如下所示:
- 基于此启动在 localhost:8080 上运行的代理:https://gist.github.com/yowu/f7dc34bd4736a65ff28d
- 启动在 localhost:10000 上运行的文件服务器
- 将我的网络浏览器配置为使用在 localhost:8080 上运行的代理
- 来自 yowu 要点第 74 行的响应我对目标 url 进行了替换
network proxy fileserver
:8080 :10000
.---------. .---------. .---------.
<----|- - < - -|---<---|- - < - -|---<---|- < -| |
you ---->|- - > - -|--->---|- -,- > -|--->---|- > -| |
| | | |(*) | | |
website<-|- - < - -|---<---|< -' | | |
| | | | | |
`---------´ `---------´ `---------´
(*) Modify the response from the fileserver to change the target URL
它确实解决了问题,但更复杂。如果知道是否还有其他更简单的方法,那就太好了。
到这里,我们也就讲完了《HTTP 文件服务器响应拦截与 URL 重写》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
