日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Go語言實現關閉http請求的方式總結_Golang

作者:nil ? 更新時間: 2023-06-18 編程語言

寫在前面

面試的時候問到如何關閉http請求,一般人脫口而出的是關閉response.body,這是錯誤的。response是返回結果的一個結構體,跟http連接沒有關系。

type Response struct {
	Status     string // e.g. "200 OK"
	StatusCode int    // e.g. 200
	Proto      string // e.g. "HTTP/1.0"
	ProtoMajor int    // e.g. 1
	ProtoMinor int    // e.g. 0
	Header Header
	Body io.ReadCloser
	ContentLength int64
	Close bool
	Uncompressed bool
	Trailer Header
	Request *Request
	TLS *tls.ConnectionState
}

Body是Response中定義的一個IO流,用來讀取返回內容。調用完成之后,無論http連接是否需要關閉,都要關閉response.body。

方式一:設置請求變量的 Close 字段值為 true

設置之后req.Close = true,每次請求結束后就會主動關閉連接

func main() {
	req, err := http.NewRequest("GET", "http://www.baidu.com", nil)
	checkError(err)

	req.Close = true

	resp, err := http.DefaultClient.Do(req)
	if resp != nil {
		defer resp.Body.Close()
	}
	checkError(err)

	body, err := ioutil.ReadAll(resp.Body)
	checkError(err)

	fmt.Println(string(body))

}

func checkError(err error) {
	if err != nil {
		fmt.Printf("err:%+v\n", err)
	}
}

方式二:設置 Header 請求頭部選項 Connection: close

設置req.Header.Add("Connection", "close")之后,然后服務器返回的響應頭部也會有這個選項,此時 HTTP 標準庫會主動斷開連接

func main() {
	req, err := http.NewRequest("GET", "http://www.baidu.com", nil)
	checkError(err)

	req.Header.Add("Connection", "close")

	resp, err := http.DefaultClient.Do(req)
	if resp != nil {
		defer resp.Body.Close()
	}
	checkError(err)

	body, err := ioutil.ReadAll(resp.Body)
	checkError(err)

	fmt.Println(string(body))

}

func checkError(err error) {
	if err != nil {
		fmt.Printf("err:%+v\n", err)
	}
}

方式三:自定義配置的 HTTP transport 客戶端

這個主要是用來取消 HTTP 全局的復用連接,調用解釋之后會自動關閉http連接

func main() {
	tr := http.Transport{DisableKeepAlives: true}
	client := http.Client{Transport: &tr}
	resp, err := client.Get("http://www.baidu.com")
	checkError(err)
	if resp != nil {
		defer resp.Body.Close()
	}

	body, err := ioutil.ReadAll(resp.Body)
	checkError(err)

	fmt.Println(string(body))

}

func checkError(err error) {
	if err != nil {
		fmt.Printf("err:%+v\n", err)
	}
}

原文鏈接:https://juejin.cn/post/7203802569201565753

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新