doubomudichen0832 2013-12-05 06:36
浏览 100
已采纳

关于HTTP劫持和保持活动状态

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 keepalivekeepalive2 keep-alive, It keep two tcp connection, and can reuse.

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

  • 写回答

2条回答 默认 最新

  • douqingnao9246 2013-12-11 06:36
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名