golang http连接复用方法
程序员文章站
2022-04-28 17:06:27
server端
golang httpserver 默认开启keepalive连接复用选项
handler函数需要完整读body数据,构造返回消息,否则当数据不能一次发...
server端
golang httpserver 默认开启keepalive连接复用选项
handler函数需要完整读body数据,构造返回消息,否则当数据不能一次发送完成时,连接复用就会失效。
示例如下
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" "strconv" "strings" "time" ) func connhandler(w http.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 } defer r.body.close() // sleep for some time resp_time := 1 if response_time != "" { ms, _ := strconv.parsefloat(response_time, 64) resp_time = (int)(ms * 1000) } time.sleep(time.duration(resp_time) * time.millisecond) // parepare response 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)) } func main() { http.handlefunc("/", connhandler) if err := http.listenandserve(":server_port", nil); err != nil { log.fatal("listenandserve: ", err) } }
client 端
客户端需要构建全局client,完整读 response body,并关闭body
package main import ( "bytes" "fmt" "io" "io/ioutil" "log" "net/http" "time" ) var ( httpclient *http.client ) const ( maxidleconnections int = 20 requesttimeout int = 30 ) // init httpclient func init() { httpclient = createhttpclient() } // createhttpclient for connection re-use func createhttpclient() *http.client { client := &http.client{ transport: &http.transport{ maxidle connsperhost: maxidleconnections, }, timeout: time.duration(requesttimeout) * time.second, } return client } func conn_reuse_post(conn_reuse_times int) { var endpoint string = "http://server_ip:server_port/" data := []byte{} // fill data for i := 0; i < conn_reuse_times; i++ { // use global httpclient to send request resp, err := httpclient.post(endpoint, "application/x-www-form-urlencoded", bytes.newbuffer([]byte(data))) fmt.println(resp) if err != nil { log.println("err", err) return } io.copy(ioutil.discard, resp.body) // <= note resp.body.close() // <= note } } func main() { conn_reuse_post(5) }
以上这篇golang http连接复用方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
下一篇: 历史上的东方朔是什么样的?他的结局如何