golang http連接復(fù)用方法
server端
golang httpserver 默認(rèn)開(kāi)啟keepalive連接復(fù)用選項(xiàng)
handler函數(shù)需要完整讀body數(shù)據(jù),構(gòu)造返回消息,否則當(dāng)數(shù)據(jù)不能一次發(fā)送完成時(shí),連接復(fù)用就會(huì)失效。
示例如下
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 端
客戶端需要構(gòu)建全局client,完整讀 response body,并關(guān)閉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連接復(fù)用方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Go?CSV包實(shí)現(xiàn)結(jié)構(gòu)體和csv內(nèi)容互轉(zhuǎn)工具詳解
這篇文章主要介紹了Go?CSV包實(shí)現(xiàn)結(jié)構(gòu)體和csv內(nèi)容互轉(zhuǎn)工具詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Golang map如何生成有序的json數(shù)據(jù)詳解
最近在學(xué)習(xí)Golang,發(fā)現(xiàn)了一個(gè)問(wèn)題,覺(jué)著有必要給大家總結(jié)下,下面這篇文章主要給大家介紹了關(guān)于Golang map如何生成有序json數(shù)據(jù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面來(lái)一起看看吧。2017-07-07
go語(yǔ)言中的json與map相互轉(zhuǎn)換實(shí)現(xiàn)
本文主要介紹了go語(yǔ)言中的json與map相互轉(zhuǎn)換實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08
Go語(yǔ)言編程實(shí)現(xiàn)支持六種級(jí)別的日志庫(kù)?
這篇文章主要為大家介紹了使用Golang編寫(xiě)一個(gè)支持六種級(jí)別的日志庫(kù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Go 語(yǔ)言結(jié)構(gòu)實(shí)例分析
在本篇文章里小編給大家整理的是一篇關(guān)于Go 語(yǔ)言結(jié)構(gòu)實(shí)例分析的相關(guān)知識(shí)點(diǎn),有興趣的朋友們可以學(xué)習(xí)下。2021-07-07
Go語(yǔ)言實(shí)現(xiàn)常見(jiàn)限流算法的示例代碼
計(jì)數(shù)器、滑動(dòng)窗口、漏斗算法、令牌桶算法是我們常見(jiàn)的幾個(gè)限流算法,本文將依次用Go語(yǔ)言實(shí)現(xiàn)這幾個(gè)限流算法,感興趣的可以了解一下2023-05-05
Golang中crypto/rand庫(kù)的使用技巧與最佳實(shí)踐
在Golang的眾多隨機(jī)數(shù)生成庫(kù)中,crypto/rand?是一個(gè)專為加密安全設(shè)計(jì)的庫(kù),本文主要介紹了Golang中crypto/rand庫(kù)的使用技巧與最佳實(shí)踐,感興趣的可以了解一下2024-02-02

