golang http连接复用方法
server端
golanghttpserver默认开启keepalive连接复用选项
handler函数需要完整读body数据,构造返回消息,否则当数据不能一次发送完成时,连接复用就会失效。
示例如下
packagemain import( "fmt" "io/ioutil" "log" "net/http" "os" "strconv" "strings" "time" ) funcconnHandler(whttp.ResponseWriter,r*http.Request){ //parse r.ParseForm() response_time:=r.Header.Get("sleep-time") //<=NOTE if_,err:=ioutil.ReadAll(r.Body);err!=nil{ http.Error(w,err.Error(),500) return } deferr.Body.Close() //sleepforsometime resp_time:=1 ifresponse_time!=""{ ms,_:=strconv.ParseFloat(response_time,64) resp_time=(int)(ms*1000) } time.Sleep(time.Duration(resp_time)*time.Millisecond) //parepareresponse status:=200 body:="" w.Header().Set("Content-Type","text/plain") w.Header().Set("Content-Length",strconv.Itoa(len(body))) w.WriteHeader(status) w.Write([]byte(body)) } funcmain(){ http.HandleFunc("/",connHandler) iferr:=http.ListenAndServe(":server_port",nil);err!=nil{ log.Fatal("ListenAndServe:",err) } }
client端
客户端需要构建全局client,完整读responsebody,并关闭body
packagemain import( "bytes" "fmt" "io" "io/ioutil" "log" "net/http" "time" ) var( httpClient*http.Client ) const( MaxIdleConnectionsint=20 RequestTimeoutint=30 ) //initHTTPClient funcinit(){ httpClient=createHTTPClient() } //createHTTPClientforconnectionre-use funccreateHTTPClient()*http.Client{ client:=&http.Client{ Transport:&http.Transport{ MaxIdleConnsPerHost:MaxIdleConnections, }, Timeout:time.Duration(RequestTimeout)*time.Second, } returnclient } funcconn_reuse_post(conn_reuse_timesint){ varendPointstring="http://server_ip:server_port/" data:=[]byte{} //filldata fori:=0;i以上这篇golanghttp连接复用方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。