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
You can see one library (martini) which introduced
hijack
: issue 45(Note: I don't recommend Martini, which is not idiomatic, but it is mentioned here only to illustrate
hijack
)That issue refers to the following go-nuts thread, where one tried to embed the interface
http.ResponseWriter
in order to record statistics like bytes written and request duration.So, if you want to take over the
ResponseWriter
in order to:Upgrade
" an HTTP server connection, callingw.(http.Hijacker)
)Then you can consider using hijack.
But, as documented, after a call to
Hijack()
, the HTTP server library will not do anything else with the connection.It becomes the caller's responsibility to manage and close the connection.
If not, as illustrating in this other question, then hijack isn't interesting.