This is a creation in Article, where the information may have evolved or changed.
Never quite understood what Golang's hijack was for? Only know hijack this word is the meaning of usurpation, and the role of the gateway, the client's request to the service, and then this service to help forward to the remote server, but read the source to understand this Golang hijack is why?
Let's take a look at the hijack related structure description:
Type hijacker interface {Hijack () (NET. Conn, *bufio. Readwriter, error)}//returns the connection interface net. Conn and Readwriter,bufio read and write.
Hijack lets the caller take over the connection. -----Translation Hijack let callers manage connections
After a call to Hijack (), the HTTP server library
Won't does anything else with the connection.
It becomes the caller ' s responsibility to manage
and close the connection.
------------Translator calls hijack, the HTTP server does not make redundant processing of the connection to allow the user to manage and close the connection themselves
And look at the use of hijack in Docker.
dial, err := cli.dial () // Set Tcp keepalive to make long connections// when we set up a tcp connection for hijack, there could be long periods// of inactivity (a long Running command with no output) that in certain// network setups may cause ECONNTIMEOUT, leaving the client in an unknown// state. setting tcp keepalive on the socket connection will Prohibit// econntimeout unless the socket connection truly is brokenif tcpconn, ok := dial. (*net. Tcpconn); ok {tcpconn.setkeepalive (True) tcpconn.setkeepaliveperiod (30 * time. Second)}if err != nil {if strings. Contains (Err. Error (), "CONNECTION&NBsp;refused ") {return fmt. Errorf ("cannot connect to the docker daemon. is ' Docker daemon ' Running on this host ")} Return err}clientconn := httputil. Newclientconn (Dial, nil) defer clientconn. Close ()// server hijacks the connection, error ' connection closed ' Expectedclientconn. Do (req) rwc, br := clientconn. Hijack () //cleanup buffer This step is very important, return this two parameters is to the user to manage the connection and data processing DEFER RWC. Close ()
And look at Clientconn. Implementation of Hijack:
Func (cc *clientconn) Hijack () (c net. Conn, R *bufio. Reader) {Cc.lk.Lock () defer cc.lk.Unlock () c = cc.cr = CC.RCC.C = NILCC.R = nilreturn}// is the Net.conn and Bufio.readerfunc Newclientconn (c net) saved at newclientconn time. Conn, R *bufio. Reader) *clientconn {if r = = Nil {r = Bufio. Newreader (c)}return &clientconn{c:c,r:r,pipereq:make (map[*http. Request]uint), Writereq: (*http. Request). Write,}}
Summary: Hijack does not need to reestablish the connection or reconstruct the Clientconn settings Net.conn and Bufio, and then continually reuse net.conn and Bufio to manage