when to use hijack in golang?

go, go-http

Solution

Use Hijack when you don't want to use the built-in server's implementation of the HTTP protocol. This might be because you want to switch protocols (to WebSocket for example) or the built-in server is getting in your way.

The two snippets of code above do not create the same output on the wire. The output from the first snippet will include a response header:

HTTP/1.1 200 OK
Date: Wed, 26 Nov 2014 03:37:57 GMT
Content-Length: 16
Content-Type: text/plain; charset=utf-8

write some thing

The second snippet bypasses the built-in server code and writes

write some thing

directly to the output.

Problem

I don't understand why we use hijack, since I can write something into response body directly, could anyone explain this? ``` func writeSome(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "write some thing") } ``` it is same as this: ``` func hijack(w http.ResponseWriter, r *http.Request) { hj, _ := w.(http.Hijacker) _, buf, _ := hj.Hijack() buf.WriteString("write some thing") buf.Flush() } ``` I am confused

Original source

Related problems