关于http劫持和保持活跃 [英] about http hijacking and keep-alive

查看:134
本文介绍了关于http劫持和保持活跃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用

  resp,err:= http.Get(http://example.com/)

获得一个http.Response,并且我想要正确写入一个http处理程序,但只有http.ResponseWriter ,所以我劫持它。

  ... 
webConn,webBuf,err:= hj.Hijack()
if err!= nil {
//处理错误
}
推迟webConn.Close()

//写入resp
resp。 Write(webBuf)
...

写入原始请求



但是当我劫持时,http连接不能重用(keep-alive),所以它很慢。



如何解决? p>

谢谢!对不起,我的游泳池英语。



update 12/9


keep-它保留了两个tcp连接,并且可以重用。





但是当我劫持时,conn.Close() ,它不能重用旧连接,所以当我每次刷新时它都会创建一个新的tcp连接。

解决方案

不要使用劫持,因为一旦劫持,HTTP服务器库不会对连接做任何其他事情,所以不能重用。



我改变方式,复制Header和Body,看起来像反向代理( http://golang.org/src/pkg/net/ http / httputil / reverseproxy.go ),是有效的。



示例:

  func copyHeader(dst,src http.Header){
for k,w:= range src {
for _,v:= range w {
dst.Add(k,v)
}
}
}

func copyResponse(r * http.Response,w http.ResponseWriter){
copyHeader(w.Header(),r.Header)
w.WriteHeader(r.StatusCode)
io.Copy(w,r.Body)
}

func处理程序(w http.ResponseWriter,r * http.Response){
resp,err:= http.Get(http://www.example.com)
if err!= nil {
//处理错误
}
copyResponse(resp,w)
}


i use

resp, err := http.Get("http://example.com/")

get a http.Response, and i want to exactly write to a http handler, but only http.ResponseWriter, so i hijack it.

...
webConn, webBuf, err := hj.Hijack()
if err != nil {
    // handle error
}
defer webConn.Close()

// Write resp
resp.Write(webBuf)
...

Write raw request

But When i hijack, http connection can't reuse (keep-alive), so it slow.

How to solve?

Thanks! Sorry for my pool English.

update 12/9 keep-alive, It keep two tcp connection, and can reuse.

but when i hijack, and conn.Close(), It can't reuse old connection, so it create a new tcp connection when i each refresh.

解决方案

Do not use hijack, Because once hijack, the HTTP server library will not do anything else with the connection, So can't reuse.

I change way, copy Header and Body, look like reverse proxy (http://golang.org/src/pkg/net/http/httputil/reverseproxy.go), Is works.

Example:

func copyHeader(dst, src http.Header) {
    for k, w := range src {
        for _, v := range w {
            dst.Add(k, v)
        }
    }
}

func copyResponse(r *http.Response, w http.ResponseWriter) {
    copyHeader(w.Header(), r.Header)
    w.WriteHeader(r.StatusCode)
    io.Copy(w, r.Body)
}

func handler(w http.ResponseWriter, r *http.Response) {
    resp, err := http.Get("http://www.example.com")
    if err != nil {
        // handle error
    }
    copyResponse(resp, w)
}

这篇关于关于http劫持和保持活跃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆