這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
一直不太明白golang的hijack是幹什麼的?只知道hijack這個詞是篡取的意思,難道跟網關的作用一樣,把client的請求發到這個服務上,然後這個服務幫忙轉寄到遠端server,但是看了源碼後就明白這個golang hijack是幹嘛的?
先看一下hijack相關的結構說明:
type Hijacker interface {Hijack() (net.Conn, *bufio.ReadWriter, error)}//返回串連介面net.Conn和ReadWriter,bufio讀寫的
// Hijack lets the caller take over the connection. -----翻譯Hijack讓調用者管理串連
// 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.
------------翻譯調用Hijack後,HTTP的server不會對串連做多餘的處理讓使用者自己管理和關閉串連
再看一下docker中對hijack的使用
dial, err := cli.dial() //設定TCP keepAlive做長串連// 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 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() //清理掉buffer 這步非常重要,返回這個兩個參數就是給使用者自己管理串連和資料處理defer rwc.Close()
再看看clientconn.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}//就是在NewClientConn時候儲存的net.Conn和bufio.Readerfunc NewClientConn(c net.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,}}
總結:hijack就是不用重建立立串連或者重新構造ClientConn設定net.Conn和bufio,然後不斷複用net.Conn和bufio,自己管理