溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

golang http連接復(fù)用方法

發(fā)布時間:2020-10-17 20:36:15 來源:腳本之家 閱讀:207 作者:liliangcsdn 欄目:編程語言

server端

golang httpserver 默認(rèn)開啟keepalive連接復(fù)用選項

handler函數(shù)需要完整讀body數(shù)據(jù),構(gòu)造返回消息,否則當(dāng)數(shù)據(jù)不能一次發(fā)送完成時,連接復(fù)用就會失效。

示例如下

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ù)用方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI