欢迎来到代码驿站!

Golang

当前位置:首页 > 脚本语言 > Golang

golang http连接复用方法

时间:2020-12-25 12:28:13|栏目:Golang|点击:

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)
}

上一篇:深入讲解Go语言中函数new与make的使用和区别

栏    目:Golang

下一篇:Golang如何调用Python代码详解

本文标题:golang http连接复用方法

本文地址:http://www.codeinn.net/misctech/36472.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有