Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about http hijacking and keep-alive

Tags:

http

go

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.

like image 776
Specode Avatar asked Dec 05 '13 06:12

Specode


1 Answers

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)
}
like image 63
Specode Avatar answered Sep 23 '22 23:09

Specode