Standard library / net/http

http.Client.CloseIdleConnections()

Ask the underlying transport to close idle connections if it supports that operation. Active requests are not canceled. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func (c *Client) CloseIdleConnections()

Working Example

Example Snippetgo
package main
import (  "fmt"  "io"  "net/http"  "net/http/httptest"  "net/http/httptrace")
func main() {  s := fixture()  defer s.Close()  c := &http.Client{Transport: &http.Transport{}}  r := must(c.Get(s.URL))  must(io.ReadAll(r.Body))  check(r.Body.Close())  c.CloseIdleConnections()  reused := true  q := must(http.NewRequest("GET", s.URL, nil))  q = q.WithContext(httptrace.WithClientTrace(q.Context(), &httptrace.ClientTrace{GotConn: func(i httptrace.GotConnInfo) { reused = i.Reused }}))  r = must(c.Do(q))  defer r.Body.Close()  fmt.Println(!reused)  c.CloseIdleConnections()}func fixture() *httptest.Server {  return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {    switch r.URL.Path {    case "/redirect":      http.Redirect(w, r, "/done", http.StatusFound)    case "/cookie":      http.SetCookie(w, &http.Cookie{Name: "demo", Value: "yes", Path: "/", HttpOnly: true})    case "/echo":      c, e := r.Cookie("demo")      if e == nil {        fmt.Fprint(w, c.Value)      }    default:      fmt.Fprint(w, "hello")    }  }))}
func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference