Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了golang的hijack篡取劫持大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

一直不太明白golang的hijack是干什么的?只知道hijack这个词是篡取的意思,难道跟网关的作用一样,把client的请求发到这个服务上,然后这个服务帮忙转发到远端server,但是看了源码后就明白这个golang hijack是干嘛的?


先看一下hijack相关的结构说明:

typeHijackerinterface{
	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()//设置TCPkeepAlive做长连接
	//WhenwesetupaTCPconnectionforhijack,thereCouldbelongperiods
	//ofinactivity(alongrunningcommandwithnooutput)thaTincertain
	//networksetupsmaycauseECONNTIMEOUT,leavingtheclienTinanunkNown
	//state.SetTingTCPKeepAliveonthesocketconnectionwillprohibit
	//ECONNTIMEOUTunlessthesocketconnectiontrulyisbroken
	iftcpConn,ok:=dial.(*net.TCPConn);ok{
		tcpConn.SetKeepAlive(true)
		tcpConn.SetKeepAlivePeriod(30*time.Second)
	}
	iferr!=nil{
		ifStrings.Contains(err.Error(),"connectionrefused"){
returnfmt.Errorf("CAnnotconnecttotheDockerdaemon.Is'dockerdaemon'runningonthishost?")
		}
		returnerr
	}
	clientconn:=httputil.NewClientConn(dial,nil)
	deferclientconn.Close()

	//Serverhijackstheconnection,error'connectionclosed'expected
	clientconn.Do(req)

	rwc,br:=clientconn.Hijack()
	//清理掉buffer这步非常重要,返回这个两个参数就是给用户自己管理连接和数据处理
	deferrwc.Close()


再看看clientconn.Hijack的实现:

func(cc*ClientConn)Hijack()(cnet.Conn,r*bufio.Reader){
	cc.lk.Lock()
	defercc.lk.Unlock()
	c=cc.c
	r=cc.r
	cc.c=nil
	cc.r=nil
	return
}
//就是在NewClientConn时候保存的net.Conn和bufio.Reader
funcNewClientConn(cnet.Conn,r*bufio.Reader)*ClientConn{
	ifr==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,自己管理

大佬总结

以上是大佬教程为你收集整理的golang的hijack篡取劫持全部内容,希望文章能够帮你解决golang的hijack篡取劫持所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。